Fix Python – Line continuation for list comprehensions or generator expressions in python

How are you supposed to break up a very long list comprehension?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]

I have also seen somewhere that people that dislike using ‘\’ to break up lines,
but never understood why. What is the reason behind this?

Fix Python – Is it Pythonic to use list comprehensions for just side effects?

Think about a function that I’m calling for its side effects, not return values (like printing to screen, updating GUI, printing to a file, etc.).
def fun_with_side_effects(x):
…side effects…
return y

Now, is it Pythonic to use list comprehensions to call this func:
[fun_with_side_effects(x) for x in y if (…conditions…)]

Note tha….

Fix Python – List comprehension rebinds names even after scope of comprehension. Is this right?

Comprehensions show unusual interactions with scoping. Is this the expected behavior?
x = “original value”
squares = [x**2 for x in range(5)]
print(x) # Prints 4 in Python 2!

At the risk of whining, this is a brutal source of errors. As I write new code, I just occasionally find very weird errors due to rebinding — even now that I know it’s a p….

Fix Python – In Python list comprehension is it possible to access the item index?

Consider the following Python code with which I add in a new list2 all the items with indices from 1 to 3 of list1:
for ind, obj in enumerate(list1):
if 4 > ind > 0:

How would you write this using list comprehension, if I have no access to the indices through enumerate?
something like:
list2 = [x for x in list1 if 4 ….

Fix Python – Pythonic way to print list items

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person(“Foo”), Person(“Bar”)]
print(“\n”.join(map(str, myList)))

I read this way is not really good :
myList = [Person(“Foo”), Person(“Bar”)]
for p in myList:

Isn’t there something like :
print(p) for p in myList

If not….

Fix Python – Python using enumerate inside list comprehension

Lets suppose I have a list like this:
mylist = [“a”,”b”,”c”,”d”]

To get the values printed along with their index I can use Python’s enumerate function like this
>>> for i,j in enumerate(mylist):
… print i,j

0 a
1 b
2 c
3 d

Now, when I try to use it inside a list comprehension it gives me this error
>>> [i,j for i,j in enumerate(my….