Home > database >  I tried creating a List comprehension in Python but I am getting a None result
I tried creating a List comprehension in Python but I am getting a None result

Time:01-23

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

CodePudding user response:

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...

CodePudding user response:

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

CodePudding user response:

You can also use

numbers = [*range(50)]

as in here

  • Related