The Python Oracle

checking the enclosed tuple

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

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

--

Chapters
00:00 Checking The Enclosed Tuple
00:18 Accepted Answer Score 3
00:36 Answer 2 Score 2
00:58 Answer 3 Score 1
01:13 Thank you

--

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

--

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

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 3


You need to brute-force the search.

Check if any of the tuples in the list have the first member as 'e'

a = [('e', 4), ('r', 2), (' ', 2), ('h', 2), ('A', 1), ('t', 1), ('y', 1)]

print(any(tup[0] == 'e' for tup in a))

Which gives:

True



ANSWER 2

Score 2


You can convert the list to a dict first:

a = [('e', 4), ('r', 2), (' ', 2), ('h', 2), ('A', 1), ('t', 1), ('y', 1)]
b = dict(a)

print(('e', 4) in a)

print('e' in b)

Outputs True twice.

This code takes advantage of a dict which will directly take a list of tuples and make the first element of each tuple into the keys. Then you can quickly search the keys of the resulting dict.




ANSWER 3

Score 1


Use a list comprehension to get the first components of every tuple. Then check using if e occurs in the resulting list using the existing approach.

a = [('e', 4), ('r', 2), (' ', 2), ('h', 2), ('A', 1), ('t', 1), ('y', 1)]
print('e' in [e[0] for e in a])
# True