Search code examples
pythonlist-comprehension

How can I run multiple expressions inside of a list comprehension python?


I was trying to write a complex list comprehension but I am not sure how I am supposed to do it. I have the following for loop which I am trying to turn into a list comprehension

number = 10
deci_list = []

for i in sorted(list(range(9)), reverse=True):
    if 2**i <= number:
        deci_list.append(1)
        number -= 2**i
    else:
        deci_list.append(0)

I was struggling to turn this into a list comprehension and this is what I have so far:

thing = sorted(list(range(9)), reverse=True)
new_thing = ['1' if 2**i <= number number -= 2**i else '0' for i in thing]

however, I do not know how to add the line number -= 2**i because it gives me an error every time I try to add it

    new_thing = ['1' if 2**i <= number number -= 2**i else '0' for i in t
hing]
                 ^^^^^^^^^^^^^^^^^^^^^
SyntaxError: expected 'else' after 'if' expression

Solution

  • You're getting a syntax error due to the assignment, =, operator. It isn't supposed to be used in a list comprehension. Here's one way to work around the situation. Note that sorted(list(range(9)), reverse=True) could be replaced with range(8, -1, -1).

    number = 10
    
    
    def operator(index):
        global number
    
        if 2 ** index <= number:
            number -= 2 ** index
            return 1
        else:
            return 0
    
    
    print([operator(index) for index in range(8, -1, -1)]) # Or: list(map(operator, range(8, -1, -1)))
    

    Edit: As suggested by @ShadowRanger in the comment section, it is generally not a good idea to play with global variables in a function as it couples the two [essentially requiring you to reset the global variable or do something similar when you want to reuse the function]. You could wrap the two in a class to make it reusable.

    However, I would recommend list comprehensions only at places where they do not compromise on readability. What you have in the original snippet is completely alright.