9

I am trying to append numbers from a generator to an empty list using a single line for loop but it returns None. I understand it can be done using a for loop with 2 lines but I was wondering what I am missing. i.e.,

>>> [].append(i) for i in range(10)

[None, None, None, None, None, None, None, None, None, None]

I was hoping to create this in one line:

>>> [].append(i) for i in range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Thank you.

4 Answers 4

19

Write a proper comprehension, without append.

>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(i for i in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Sign up to request clarification or add additional context in comments.

Comments

1

Adding Explanation as to what happens, Append doesn't return anything,

y = []
x = [y.append(i) for i in range(10)]
print(x)
print(y)

produces

[None, None, None, None, None, None, None, None, None, None]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[Program finished]

Comments

0

you can also just cast a range which is a iterable:

list(range(10))
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

also for numpy users:

np.arange(10)
>>> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

or you can use linspace if its more understandable to you (linspace(from,to,pieces)) :

np.linspace(0,9,10)
>>> array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])

Comments

-2

y = []

[y.append(i) for i in range(10)]

print(y)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

1 Comment

This is the same solution as in this other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.