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:?

closed

1 Answer

0 votes
by (106k points)
edited by
 
Best answer

 For finding one element or None use default in next, it won't raise StopIteration if the item was not found in the list:

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

To know more about this you can have a look at the following video tutorial:-

Related questions

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

Browse Categories

...