Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for and if on one line

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?

like image 459
rostonik Avatar asked Sep 15 '15 07:09

rostonik


People also ask

How do you write an if and for one line in Python?

To put an if-then-else statement in one line, use Python's ternary operator x if c else y . This returns the result of expression x if the Boolean condition c evaluates to True . Otherwise, the ternary operator returns the alternative expression y .

Can you have two for statements in one line in Python?

These statements can very well be written in one line by putting semicolon in between. However, this practice is not allowed if there is a nested block of statements.

Can we write if-else in one line in Python?

Python If Statement In One Line In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. In Python, it is permissible to write the above block in one line, which is similar to the above block.


7 Answers

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
like image 165
Martijn Pieters Avatar answered Oct 06 '22 07:10

Martijn Pieters


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

like image 32
Cong Ma Avatar answered Oct 06 '22 06:10

Cong Ma


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
like image 31
desiato Avatar answered Oct 06 '22 07:10

desiato


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]
like image 35
Jin Avatar answered Oct 06 '22 07:10

Jin


In python3 the variable i will be out of scope when you try to print it.

To get the value you want you should store the result of your operation inside a new variable:

my_list = ["one","two","three"]
result=[(i) for i in my_list if i=="two"]
print(result)

you will then get the following output

['two']
like image 35
Americain Naif Avatar answered Oct 06 '22 06:10

Americain Naif


Found this one:

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

Will print:

["two"]
like image 28
Hugo Arganda Avatar answered Oct 06 '22 05:10

Hugo Arganda


The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:

arr = []
for i in array :
    if i == "two" :
        arr.push(i)
print(i)

You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.

The english equivalent of what you are doing is:

You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"

The reason 'i' is equal to "three" is because three was the last thing that was defined as I

the computer did:

i = "one"
i = "two"
i = "three"

print(["two"])

Because you asked it to.

If you want the index, go here If you want the values in an array, define the array, like this:

MyArray = [(i) for i in my_list if i=="two"]
like image 39
MartinNajemi Avatar answered Oct 06 '22 07:10

MartinNajemi