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, ...
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, ...
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...
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)]