Extracting elements over multiple lists?

Laurent Claessens moky.math at gmail.com
Mon Nov 7 12:44:59 EST 2011


Le 07/11/2011 18:12, JoeM a écrit :
> Howdy,
>
> If I have a few lists like
>
> a=[1,2,3,4,5]
> b=["one", "two", "three", "four", "five"]
> c=["cat", "dog", "parrot", "clam", "ferret"]
>
> what is the most pythonic method of removing the first element from
> all of the lists?

Do you want to remove the first item of each list, or to create new 
lists that contain the same as a,b,c but with one element less ?

Something like what you wrote :
[arr[1:] for arr in a,b,c]
will create *new* lists.


Assuming you don't want new lists, I would do :

a=[1,2,3,4,5]
b=["one", "two", "three", "four", "five"]
c=["cat", "dog", "parrot", "clam", "ferret"]

for x in [a,b,c]:
     x.remove(x[0])

print a
print b
print c

I think that writing
 >>> [x.remove(x[0]) for x in [a,b,c]]
instead of the for loop is cheating ... but it also does the job.

Have a good after noon
Laurent












More information about the Python-list mailing list