Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: List Reversing on One Line [duplicate]

Tags:

python

ls = list(range(10))
ls.reverse()
print(ls)

Why does this work in producing a list that counts backwards from 9 not but not this:

ls = list(range(10)).reverse()
print(ls)

These last two lines prints this instead:

None

Shouldn't they be the same thing?

like image 255
harold__hadrada Avatar asked Aug 24 '26 13:08

harold__hadrada


1 Answers

No, because list.reverse() returns None since it reverses the list in place. See the list documentation

You could use reversed() like so:

countdown = list(reversed(range(10)))
print(countdown)

See the reversed documenation

See also this question

like image 71
John Cummings Avatar answered Aug 26 '26 03:08

John Cummings