0

which is a pythonic and style guide compliant way of operation in case of the following three scenarios.

sq, div2 = [], []

# 1 Classic for loop
for i in range(10):
    sq.append(i**2)
    div2.append(i/2)

# 2 ListComp
[(sq.append(i**2), div2.append(i/2)) for i in range(10)]

# 3 single line for loop
for i in range(10):(sq.append(i**2), div2.append(i/2))

# this is also there but will have multiple loops
sq, div2 = [[i**2 for i in range(10)], [i/2 for i in range(10)]]

or any better way whereby a single for loop generates multiple lists and assign vars.

Rahul
  • 10,830
  • 4
  • 53
  • 88
  • A list comprehension is basically a `map`, and the purpose of `map` is to take one list and transform it into a new list via some mapping function/expression. Don't use a comprehension if your intent is just to carry out side effects. – Carcigenicate Jul 20 '19 at 12:35
  • At least for 2 and 3: https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects and 4 is bad because you're forcing two definitions onto one line instead of putting them over two. – Carcigenicate Jul 20 '19 at 12:40
  • The outer list is also an unnecessary (however slightly) expense; `sq, div2 = [i**2...], [i/2 ...]` would be sufficient. – chepner Jul 20 '19 at 12:46

1 Answers1

4

The first is absolutely the best choice of the four you list.

Don't use a list comprehension unless you actually want the list it produces, and don't cram a for loop on to one line just to make it a one-liner. Having two loops seems a definite drawback to the fourth; you are repeating yourself a bit more than necessary, although you should profile to see if the double iteration makes a significant difference in the runtime. I suspect you would need to be generating very long lists before the difference between one loop and two really matters, though.


However, there is one option you have overlooked: producing a sequence of tuples, then "unzipping" it into a tuple of tuples.

sq, div2 = zip(*((i**2, i/2) for i in range(10)))

I think I would still prefer to see the first one, though. It's clearer, without requiring the reader to recognize the unzip idiom.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I also liked the first option. In my case there are 4 append operations pe loop, so it will be broken to multiple lines anyway. Thanks – Rahul Jul 20 '19 at 14:09