Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have come across this:

item = someSortOfSelection() 

if item in myList: 

doMySpecialFunction(item)

but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string).

Is this the most 'pythonic' way of finding an item in a list: if x in l:?

1 Answer

0 votes
by (106k points)

To find one element or None use default in next, it will not raise StopIteration if the item was not found in the list:

first_or_default = next((x for x in lst if ...), None)

Related questions

0 votes
1 answer
asked Aug 24, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...