Python for and if on one line
Python for and if on one line
You are producing a filtered list by using a list comprehension. i
is still being bound to each and every element of that list, and the last element is still three
, even if it was subsequently filtered out from the list being produced.
You should not use a list comprehension to pick out one element. Just use a for
loop, and break
to end it:
for elem in my_list:
if elem == two:
break
If you must have a one-liner (which would be counter to Pythons philosophy, where readability matters), use the next()
function and a generator expression:
i = next((elem for elem in my_list if elem == two), None)
which will set i
to None
if there is no such matching element.
The above is not that useful a filter; your are essentially testing if the value two
is in the list. You can use in
for that:
elem = two if two in my_list else None
When you perform
>>> [(i) for i in my_list if i==two]
i
is iterated through the list my_list
. As the list comprehension finishes evaluation, i
is assigned to the last item in iteration, which is three
.
Python for and if on one line
In list comprehension the loop variable i becomes global. After the iteration in the for loop it is a reference to the last element in your list.
If you want all matches then assign the list to a variable:
filtered = [ i for i in my_list if i==two]
If you want only the first match you could use a function generator
try:
m = next( i for i in my_list if i==two )
except StopIteration:
m = None