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]
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.
y = []
for e in x:
if e == 2:
break
y.append(e)
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With