Skip to content
Advertisement

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

JavaScript

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

JavaScript

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

JavaScript

Advertisement

Answer

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

JavaScript

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement