checking the enclosed tuple

Viewed 101

this code returns True

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

and if I don't know the number next to 'e', ​​how do I check if that letter is on the list

print(('e',) in a) # False
3 Answers

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

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.

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
Related