7

I've searched for a relevant thread on how to do this but I cannot find anything.

I have an array:

x = [a,a,a,b,a,a]

I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried initializing y but that didn't work either. Any ideas? I'm sure there is a better way to do this.

for ii in x:
    if x[ii].find(num) == 0:
        break
    else:
        y[ii] = x[ii]
2
  • 1
    What do u mean by x[ii].find(num)? You have a list of integers or strings? Commented Aug 5, 2016 at 13:01
  • Sorry, I used integers as an example, its an array of strings. Fixed. Commented Aug 5, 2016 at 13:03

6 Answers 6

5

Try this:

x = [1,1,1,2,1,1]
b = 2

try:
    y = x[:x.index(b)]
except ValueError:
    y = x[:]

For example:

In [10]: x = [1,1,1,2,1,1]
    ...: b = 2
    ...: 
    ...: try:
    ...:     y = x[:x.index(b)]
    ...: except ValueError:
    ...:     # b was not found in x. Just copy the whole thing.
    ...:     y = x[:]
    ...:

In [11]: y
Out[11]: [1, 1, 1]

See list.index() and the shallow-copy slice for more information.

Sign up to request clarification or add additional context in comments.

Comments

3
y = []
for e in x:
    if e == 2:
        break
    y.append(e)

?

3 Comments

Also known as y = x[:x.index(2)].
Mephy: right. Just thought the author needs some plain implementation.
@IgorPomaranskiy Besides the implementation, some explanation would also be nice,
2

You could use itertools.takewhile:

>>> x = [1,1,1,2,1,1]
>>> import itertools
>>> y = list(itertools.takewhile(lambda i: i != 2, x))
>>> y
[1, 1, 1]

When using a loop, you have to use y.append; if you do y[ii] = ..., then you will get an IndexError as you try to set e.g. the first element of an array that has zero elements. Also, when you loop like this for ii in x: then ii is already the element from x, i.e. you do not have to do x[ii]. In your case, this did not give an exception, since x[1] would be a valid element of x, but it would not be what you expected.

Comments

2

I would split the array by the b index:

>>> x = ['a','a','a','b','a','a']
>>> c = x.index('b')
>>> x[:c]
['a', 'a', 'a']
>>> x[c:]
['b', 'a', 'a']

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
1

Way to get things done with generator expression:

x = ['a', 'a', 'a', 'b', 'a', 'a']
items = list(next(iter([])) if item == 'b' else item for item in x)
print items
['a', 'a', 'a']

4 Comments

Wow, using next(iter([])) to trigger StopIteration in a list comprehension. I'm not sure whether I should upvote this, but certainly a creative solution. ;-)
@tobias_k thanks, your comment is better than upvoting )))
BTW, actually, this is a generator expression, not a list comprehension. With a proper list comprehension this would not work.
Cool and creative .. +1
0

Though it is somehow similar to Will's answer, but in here it shows the use of slice built-in slicing object:

>>> x = ['a','a','a','b','a','a']
>>> s = slice(x.index('b'))
>>> 
>>> x[s]
['a', 'a', 'a']

2 Comments

Can you also use this method with an object of type 'dict'?
You mean a list of dict ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.