Beginner question: assigning variable to list.reverse()

Any idea why assigning variable Y to this does not result in anything?

create a list of prime numbers

x = [2, 3, 5, 7]

reverse the order of list elements

y=x.reverse()
print(y)

reverse modifies the list in-place, so obviously returns None. If you want a new list, call reversed instead. This kind of thing is documented - see the standard library documentation on the sequence types.

1 Like

As @ndc86430 says.

So, to keep the original list as is and create a new reversed version:

x1 = [2, 3, 5, 7]
x2 =[]
y = reversed(x1)
for x in y:
    x2.append(x)
print(x1)
print(x2)

Thank you,

however why does it print this then in reversed order?

create a list of prime numbers

x = [2, 3, 5, 7]

reverse the order of list elements

x.reverse()
print(x)

this works for x. But assiging new variable Y and it doesn’t print Y

OK I got it i Think. Reversse doesn’t give values. It just updates the list of x.
If i need a new reversed list called y i would do

x = [2, 3, 5, 7]
y=list(x)
y.reverse()
print(y)

Thanks for mentioning me! Just learning sorry. appreciate it.

By Hans Heytens via Discussions on Python.org at 12May2022 10:20:

OK I got it i Think. Reversse doesn’t give values. It just updates the
list of x.

Yes. To avoid an accident where you think you have a new, separate,
list there is a convention in Python that a function which changes
something in place returns None so that you can’t proceed thinking you
have a new thing. You’ve just got the old thing, modified.

So somelist.reverse() changes things in place and returns None.

If i need a new reversed list called y i would do

Yes. I detail:

x = [2, 3, 5, 7]

Original list.

y=list(x)

A new list created from the elements of x.

y.reverse()

Modify the new list in place.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

much appreciated!