-1

This is my Python code

numbers = []

for i in range(20):
    numbers.append(i)

print(numbers)

This is my list comprehension

numbers = [numbers.append(i) for i in range(50)]
print(numbers)

The result I am getting is None, None, None, ...

manntala
  • 15
  • 4

3 Answers3

5

You've got a slight misunderstanding about what list comprehension is or should be used for.

If you just want a list of consecutive numbers, numbers = list(range(20)) does the trick.

But let's assume you want something more special. Then what you should write is something like

numbers = [i for i in range(50)]

What happens in your case is that for 50 times you call append(i) on numbers. That append method does indeed append the number to the list, but it doesn't return anything. And because it doesn't return anything, you're just collecting 50 times None in your example...

cadolphs
  • 9,014
  • 1
  • 24
  • 41
0

You're getting None because that is the return value of .append().

You don't need .append() anyway. Use this instead:

numbers = [i for i in range(50)]
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

You can also use

numbers = [*range(50)]

as in here

dudung
  • 499
  • 2
  • 17
  • @john-gordon and @cadolphs already explain where `None` comes from. I just put shorter way to produce list from range but actually without list comprehension. – dudung Jan 22 '23 at 23:45