Reputation: 12645
I have a list which looks like this:
List = [['name1','surname1'], ['name2','surname2'],['name3','surname3']]
I would like to check if "name1" is in the object "List". I have tried:
if 'name1' in List:
print True
else:
print False
and the output is 'False'. Any idea how to create a sublist (or something similar) to check the first element of every sub-list without looping through all the elements of the main list?
POSSIBLE SOLUTION
What I have thought about is:
for i in range(0, len(List)):
if List[i][0] == 'name1':
print True
but I want to avoid exactly this iteration with something more optimized, if possible.
Upvotes: 1
Views: 4709
Reputation: 239443
More idiomatic way to do this, is to use any
function
>>> any('name1' == current_list[0] for current_list in my_list)
True
This also short circuits on the first occurrence of name1
.
Edit : In case, your name1
can be anywhere in the sub-list, you can use the in
operator
>>> any('name1' in current_list for current_list in my_list)
True
Upvotes: 1
Reputation: 250891
You can use a generator expression:
>>> 'name1' in (x[0] for x in List)
True
This will short-circuit as soon as 'name1'
is found and won't create any unnecessary list in memory.
Related: List comprehension vs generator expression's weird timeit results?
Upvotes: 7
Reputation: 29794
You can do it with:
if 'name1' in [l[0] for l in List]:
You can also add an if l
at then end of the list comprehension just in case there's an empty list around:
if 'name1' in [l[0] for l in List if l]: # safe if there's an empty list
Upvotes: 1
Reputation: 315
I suggest using a dictionary, which seems more suitable here.
But if a list of lists is to be used, you can have such a code: 'name1' in [list[0] for list in List]
Upvotes: 2