The Python Oracle

Find an element in a list of tuples

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Find An Element In A List Of Tuples
00:19 Accepted Answer Score 317
00:35 Answer 2 Score 29
00:50 Answer 3 Score 10
00:57 Answer 4 Score 12
01:01 Thank you

--

Full question
https://stackoverflow.com/questions/2191...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #search #tuples

#avk47



ACCEPTED ANSWER

Score 317


If 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]



ANSWER 2

Score 29


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 == value :
            yield x,y

result= list( filter_value( a, 1 ) )



ANSWER 3

Score 12


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



ANSWER 4

Score 10


for item in a:
   if 1 in item:
       print item