Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 922
iheartcpp Avatar asked Feb 07 '23 10:02

iheartcpp


2 Answers

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.

like image 151
Will Avatar answered Feb 13 '23 06:02

Will


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

?

like image 37
Igor Pomaranskiy Avatar answered Feb 13 '23 05:02

Igor Pomaranskiy