1

Is it possible to append multiple list during list comprehension? For example: Below works fine:

X = []
Y = []
[X.append(i) for i in range(100000)]

But, this won't even run:

[X.append(i), Y.append(i**2 + 3*i) for i in range(100000)]

How to make above work?

Anant
  • 206
  • 2
  • 8

4 Answers4

2

You should never write the code you've written above.

[X.append(i) for i in range(...)] generates the result [None, None, None, ......] where there are 100,000 Nones in that list, and then throws it away. It just so happens that X.append(i) has a side affect that you're taking advantage of.

You're looking for

X.extend(i for i in range(100000))

And as for the code you're trying to write. Just make it two lines of code. Your readers will thank you.

Or alternatively, just X = [i for i in range(100000)] and likewise for Y.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
0

Direcly define your list with comprehension:

Y = [i**2 + 3*i for i in range(1000)]
PlainRavioli
  • 1,127
  • 1
  • 1
  • 10
0

You can use zip(*...) (transposing operation) to assign to different variables:

X, Y = map(list, zip(*((i, i ** 2 + 3 * i) for i in range(10))))

print(X)
print(Y)

Prints:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 4, 10, 18, 28, 40, 54, 70, 88, 108]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

To answer your question, you need to wrap your two parameters in brackets to be able to do that from within list comprehension:

[(X.append(i), Y.append(i**2 + 3*i)) for i in range(100000)]

However, doing it this way is unpythonic as it will result in a list filled with None of length 10_000 which immediately gets discarded. Just use a for loop:

for i in range(10_000):
  X.append(i)
  Y.append(i**2 + 3*i)

or, two list comprehensions:

X = list(range(10_000))
Y = [i**2 for i in range(10_000)]
Tom McLean
  • 5,583
  • 1
  • 11
  • 36