Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - iterating over a subset of a list of tuples

Tags:

python

Lets say I have a list of tuples as follows

l = [(4,1), (5,1), (3,2), (7,1), (6,0)]

I would like to iterate over the items where the 2nd element in the tuple is 1?

I can do it using an if condition in the loop, but I was hoping there will a be amore pythonic way of doing it?

Thanks

like image 552
dopplesoldner Avatar asked Aug 08 '13 16:08

dopplesoldner


1 Answers

You can use a list comprehension:

[ x for x in l if x[1] == 1 ]

You can iterate over tuples using generator syntax as well:

for tup in ( x for x in l if x[1] == 1 ):
    ...
like image 138
jh314 Avatar answered Nov 14 '22 21:11

jh314