Search code examples
pythonfor-looplist-comprehension

Convert comprehension to a for loop in python


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]

Solution

  • 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