Python for and if on one line

271,283

Solution 1

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 Python's 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

Solution 2

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".

Solution 3

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

Solution 4

Short answer:

  1. one line loop with if statement
my_list = [1, 2, 3]
[i for i in my_list if i==2]
  1. one line loop with both if and else statement. unfortunately, we can't put if-else statement in the end like above.
[i if i==2 else "wrong" for i in my_list]

Solution 5

Found this one:

[x for (i,x) in enumerate(my_list) if my_list[i] == "two"]

Will print:

["two"]
Share:
271,283

Related videos on Youtube

rostonik
Author by

rostonik

Updated on July 09, 2022

Comments

  • rostonik
    rostonik almost 2 years

    I have a issue with python.

    I make a simple list:

    >>> my_list = ["one","two","three"]
    

    I want create a "single line code" for find a string.

    for example, I have this code:

    >>> [(i) for i in my_list if i=="two"]
    ['two']
    

    But when I watch the variable is wrong (I find the last value of my list):

    >>> print i
    three
    

    Why does my variable contain the last element and not the element that I want to find?

    • khelwood
      khelwood over 8 years
      If you want to find a list of items matching some criteria, then use [i for i in my_list if ...]. If you want to find one item matching some criteria, consider using next; e.g. x = next(i for i in my_list if ...)
    • matt
      matt over 8 years
      i will not contain the value, it is still assigned all of the values. The result will only contain the values that meet the criteria.
    • The6thSense
      The6thSense over 8 years
      you are not wrong and your interpreter is not wrong it is just that the loop goes till the last value even if the condition is not satisfied so you are getting "three" to avoid that you could do what @khelwood said
    • Tim Pietzcker
      Tim Pietzcker over 8 years
      Why aren't you using "two" in mylist (which returns a boolean) or mylist.index("two") (which returns the position of the found string)? Since you already have the string you're looking for, it's pointless to have it returned yet again by the search, isn't it?
  • rostonik
    rostonik over 8 years
    Hi, i resolve this issue with this code: res = [(i) for i in my_list if i=="two"] ! It's correct?
  • Duncan
    Duncan over 8 years
    I think it is worth mentioning that i is only assigned to the last item in old (pre 3.x) versions of Python. In Python 3.x the variable scope is limited to inside the list comprehension so outside the comprehension you will see the previous value of i, or it will be undefined if it had no previous value.
  • matt
    matt over 8 years
    @Cong Ma you rejected an edit, that actually addressed the issue OP wasn't assigning the result to a value.
  • Cong Ma
    Cong Ma over 8 years
    He asked "Why ..." and this is an answer. It's up to himself whether to assign this to anything if at all.
  • Dee
    Dee about 3 years
    how about 'else'?
  • Yasmine
    Yasmine over 2 years
    can't i do it withouut the [ ] ?!!