tags:

views:

85

answers:

4

I have a list 'a'

a= [(1,2),(1,4),(3,5),(5,7)]

I need to find all the tuples for a particular number. say for 1 it will be

result = [(1,2),(1,4)]

How do I do that.

PS - This is not homework

+4  A: 

I you just want the first number to match you can do it like this:

[item for item in a if item[0] == 1]

If you are just searching for tuples with 1 in them:

[item for item in a if 1 in item]
Nadia Alramli
+2  A: 

Read up on List Comprehensions

[ (x,y) for x, y in a if x  == 1 ]

Also read up up generator functions and the yield statement.

def filter_value( someList, value ):
    for x, y in someList:
        if x == 1:
            yield x,y

result= list( filter_value( a, 1 ) )
S.Lott
A: 
for item in a:
   if 1 in item:
       print item
+1  A: 
[tup for tup in a if tup[0] == 1]
Tendayi Mawushe