iheartcpp
iheartcpp

Reputation: 381

Copying part of a list in Python

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]

Upvotes: 7

Views: 28585

Answers (6)

tokhi
tokhi

Reputation: 21618

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']

Upvotes: 2

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22031

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']

Upvotes: 1

Iron Fist
Iron Fist

Reputation: 10951

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']

Upvotes: 0

Will
Will

Reputation: 24699

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.

Upvotes: 5

tobias_k
tobias_k

Reputation: 82899

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.

Upvotes: 2

Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5611

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

?

Upvotes: 3

Related Questions