Home > database >  Convert comprehension to a for loop in python [duplicate]
Convert comprehension to a for loop in python [duplicate]

Time:10-03

I have this line of code, and I'm just wondering what it would be equivalent to as a for loop.

lst = [x for x in l if x !=0]   [x for x in l if x == 0]

CodePudding user response:

addition of lists is concatenation so:

lst = []

for x in l:
    if x != 0:
        lst.append(x)
        
for x in l:
    if x == 0:
        lst.append(x)

more on that: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

  • Related