Question

I have a list of tuples:

MyList = [('name1', 'surname1', 'age1'), ('name2', 'surname2', 'age2'), ...]

I would like to make a check "if 'name2' in MyList, something like:

if 'name2' in MyList[?][0]: 
    print "do something"

If I would write if 'name2' in MyList[0] I would be accessing the element ('name1', 'surname1', 'age1') while what I meant is to access the element at position 0 of every tuple in the list. I guess there is a syntaxis to do that but I'm a newbie and cannot find it online myself, can anyone help me with this?

Was it helpful?

Solution

You can use any function and a generator function, like this

if any("name2" in name for name, surname, age in my_list):
    # do something

Here all the elements of tuples are unpacked to name, surname, age while iterating. So, we can simply check if name2 is in name. This is the same as writing

if any("name2" in current_item[0] for current_item in my_list):

This will be efficient, as it yields True immediately after there is a match, rest of the items need not be checked.

If you are looking for a way to compare two strings, you should be using == operator, like this

if any("name2" == name for name, surname, age in my_list):
# do something

OTHER TIPS

Sounds that you could benefit from using dictionaries:

my_dict = dict( (x[0],(x[1],x[2])) for x in MyList)

Then you can check for existence 'names2' in my_dict and also access directly the data my_dict['names2']

I am not sure if this is the most efficient method, but you could use this.

>>>MyList = [('name1', 'surname1', 'age1'), ('name2', 'surname2', 'age2'), ...]
>>> if 'name2' in zip(*MyList)[0]:
              #do something. 

The point is it creates a transpose of the original list. Caveat: All tuples have to be of same length to avoid data loss.

EDIT: Official docs for zip.

Official docs for * operator used in unpacking argument lists.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top