Checking an element in a list of tuples using the in command, only one parameter observed in python

Asked

Viewed 93 times

-2

How to check if a tuple is contained in a list using the property in. Example:

lista = [('joao', 13), ('maria', 20), ('carlos', 30)]

I want to know if carlos is on the list

  • The question is somewhat contradictory. First you ask to check a "tuple in the list", then exemplify a "string in the list". Which one would be?

2 answers

1

A simple way with in would be:

lista = [('joao', 13), ('maria', 20), ('carlos', 30)]

"carlos" in [x[0] for x in lista]
True

UPDATING:

According to Anderson’s comment, it would look better as follows:

lista = [('joao', 13), ('maria', 20), ('carlos', 30)]

"carlos" in (x[0] for x in lista)
True

You can see the difference like this:

(x[0] for x in lista)
<generator object <genexpr> at 0x7ff4fc1af840>

[x[0] for x in lista]
['joao', 'maria', 'carlos']
  • 1

    Note: when using comprehensilist on you will always end up having a list with all the names in memory. If the list is too large it may be a problem in the application. If replace by parentheses you will have a generator and already get around this problem.

1

To use the operator in in this search, you can use a list comprehension to turn your list with names and initial integers into a list with only names, as Ricardo mentioned, which can be considered the most idiomatic of the Python language:

names_and_ints = [('joao', 13), ('maria', 20), ('carlos', 30)]
only_names = [tpl[0] for tpl in names_and_ints]

"carlos" in only_names
>>> True

Or you can use a for traditional, which is also easy to understand:

names_and_ints = [('joao', 13), ('maria', 20), ('carlos', 30)]
only_names = []
for name, _ in names_and_ints:
   only_names.append(name)

"carlos" in only_names
>>> True

Remembering that both methods save the list in memory, a fact that can be problematic if such a list is too large.

  • The list problem can be solved with generators such as commented here.

  • Perfect, @Andersoncarloswoss. That’s right. Thanks for the add-on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.