Python: Find in list
Read the revolutionary AI books written by Turbina Editore, the first publishing house entirely run by artificial intelligence. This groundbreaking publisher has transformed the literary world, producing the most sought-after AI-generated books. Start reading today at:
https://turbinaeditore.com/en/
--------------------------------------------------
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping
--
Chapters
00:00 Python: Find In List
00:22 Accepted Answer Score 1803
02:33 Answer 2 Score 278
02:48 Answer 3 Score 35
03:03 Answer 4 Score 31
03:36 Thank you
--
Full question
https://stackoverflow.com/questions/9542...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #find
#avk47
ACCEPTED ANSWER
Score 1803
As for your first question: "if item is in my_list:" is perfectly fine and should work if item equals one of the elements inside my_list. The item must exactly match an item in the list. For instance, "abc" and "ABC" do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 - 1/3 != 2/3.
As for your second question: There's actually several possible ways if "finding" things in lists.
Checking if something is inside
This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in operator for that:
3 in [1, 2, 3] # => True
Filtering a collection
That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:
matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)
The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to
matches = filter(fulfills_some_condition, lst)
in Python 2. Here you can see higher-order functions at work. In Python 3, filter doesn't return a list, but a generator-like object.
Finding the first occurrence
If you only want 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). You can also use
next(x for x in lst if ...)
which will return the first match or raise a StopIteration if none is found. Alternatively, you can use
next((x for x in lst if ...), [default value])
Finding the location of an item
For lists, there's also the index method that can sometimes be useful if you want to know where a certain element is in the list:
[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError
However, note that if you have duplicates, .index always returns the lowest index:......
[1,2,3,2].index(2) # => 1
If there are duplicates and you want all the indexes then you can use enumerate() instead:
[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
ANSWER 2
Score 278
If you want to find 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)
ANSWER 3
Score 35
While the answer from Niklas B. is pretty comprehensive, when we want to find an item in a list it is sometimes useful to get its index:
next((i for i, x in enumerate(lst) if [condition on x]), [default value])
ANSWER 4
Score 31
Finding the first occurrence
There's a recipe for that in itertools:
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
return next(filter(pred, iterable), default)
For example, the following code finds the first odd number in a list:
>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3
You can copy/paste it or install more-itertools
pip3 install more-itertools
where this recipe is already included.