[python] 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?

The answer is


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

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 the following output

['two']

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


Found this one:

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

Will print:

["two"]

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to list-comprehension

Python for and if on one line Inline for loop Are list-comprehensions and functional functions faster than "for loops"? How to frame two for loops in list comprehension python List comprehension on a nested list? One-line list comprehension: if-else variants Transpose a matrix in Python Why is there no tuple comprehension in Python? remove None value from a list without removing the 0 value Pythonic way to print list items