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)

Answer to your first question: Your code is perfectly fine and it should work if the variable item equals one of the elements inside your list which is myList. It maybe possible that you try to find a string that does not exactly match one of the items or maybe you are using a float value which suffers from inaccuracy.

Now coming back to your second question, so there are a lot of ways to finding things in a list some important ways I am discussing here:-

The first thing you can do is check if something is inside the list or not:-

So you can describe this by checking whether something is inside a list or not. To check whether something is inside the list or not that you can use the in operator.

E.g:-

3 in [1, 2, 3]

image

Another thing you can find something in the list by Finding the first occurrence of that thing:-

To check the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known).

For that you can also use the below-mentioned method:-

next(x for x in my_list if ...)

The above code will return the first match or raise a StopIteration if none is found. 

Related questions

0 votes
1 answer
asked Nov 19, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Aug 24, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...