Home > OS >  How to efficiently see if element is in a list of tuples
How to efficiently see if element is in a list of tuples

Time:10-15

Perhaps this has been asked before, but I keep having this problem and I wanted to know how this can be done most efficiently

The question is: How do you efficiently check if an element is in a list of tuples?


I have a list of tuples--named 'categories'--which takes in a tuple consisting of a category name and a number for the category.

I want to find if the category name a user inputs is actually a category inside of this list of tuples.

For example:

categories = [('Exam', 15), ('Homework', 20)]

Now the program asks the user for an category input:

user_category_input = input('Please enter a category name: ')
user_category_input = user_category_input.strip()

Now, I want the program to check and see if the user input for category name is actually a category in the list of tuples. If the user inputs "Exam", obviously, it is true! "Exam" is a category in the list of tuples. If it is "Presentations" then it is false etc.

The simple solution I have been using is to simply iterate through the tuples and check if the first element equals user input as this code shows:

for category in categories:
   if category[0] == user_category_input:
      return True

return False

But is this the most efficient way?

Is it possible to use some sort of lambda here? Does it make a difference to make it more efficient here?

Still learning python and just trying to see what should be done in practice so sorry if this is redundant or just a silly question :p

CodePudding user response:

Use any()

return any(c[0] == user_category_input for c in categories)

But if you need to do this frequently, it would be better to make categories a dictionary instead of a list of tuples.

CodePudding user response:

Make it into a dict. It is the appropriate data type to use for this data:

>>> dict(categories)
{'Exam': 15, 'Homework': 20}

categories = {'Exam': 15, 'Homework': 20}
return user_category_input in categories

If it must remain a list of tuples you could make a set of each category using zip:

cats = set(next(zip(*categories))
{'Exam', 'Homework'}

Then check for membership:

return user_category_input in cats
  • Related