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)
Any idea why assigning variable Y to this does not result in anything?
x = [2, 3, 5, 7]
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.
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?
x = [2, 3, 5, 7]
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
much appreciated!
From above:
âIf you want a new list, callreversed()
instead.â
To wrap up this mention of reversed()
and provide some context for newer programmers reading this thread, some redress about what reversed()
is and what it does might be informative here. This also illustrates an interesting element of the Python language: the difference between an âiterable objectâ and an âiteratorâ.
As worked out between the lines in various posts above, reversed()
creates an iterator [docs.python], not a list as one might expect.
In essence, the reversed()
iterator is a wrapper for iterable objects that adds iteration methods to the wrapped object. To demonstrate: if we create a list and try to invoke an iterator method on it directly, using next()
for example, we get an error.
>>> x = [0, 1, 2, 3]
>>> next(x)
[Traceback...]TypeError: 'list' object is not an iterator
However , reversed()
creates an iterator with the iterable object embedded in it. The command line shows that reversed(x)
is a list_reverseiterator
object. We can also see that assigning y = reversed(x)
creates a new object y
, not a reference to reversed(x)
. The memory addresses are different.
>>> reversed(x)
<list_reverseiterator object at 0x0000027E3D460490>
>>> y = reversed(x)
>>> y
<list_reverseiterator object at 0x0000027E3D460850>
>>> y is reversed(x)
False
>>> y is x #The result of this is pretty obvious but is done for completeness
False
So you can see that reversed()
is an iterator (more accurately: reversed()
creates an iterator). The command line shows that reversed(x)
is an object. To be specfic, it wraps an object with internal methods such as __next__
that will respond to the built-in function next()
. It creates an iterator that streams the list
object it was wrapped around in reverse sequence.
>>> next(y)
3
>>> y.__next__() #discouraged use of a "dunder"[1] to show the method now exists
2
[1] See the first few paragraphs HERE.
And the reversed()
iterator adds the âiterator exhaustedâ flag (all items have been streamed) .
>>> next(y)
1
>>> next(y)
0
>>> next(y)
[Traceback...]StopIteration #Iterator exhausted
>>> x
[0, 1, 2, 3] #The iterated object is fully intact
Python also provides a general iter()
function [docs.python].
P.S. I posted this because reversed()
was mentioned very briefly early on but not taken up to show its correct usage. If youâd like to discuss iterators in depth, then please start a new topic about iterators. If this post contains any errors or could use clarification, please PM me and I will revise it.
IMPORTANT: This thread is about elementary concepts. Detailed technical discussions in a beginner OPâs thread are not only off-topic but create an unfriendly atmosphere for beginners.
The easiest way to make a copy of a list and reverse it is by slicing:
mylist = [2, 4, 8, 16, 32]
rev = mylist[::-1]
print(rev) # [32, 16, 8, 4, 2]
No messing about with iterators, or having to call the list() constructor, or making a copy and then call reverse. Just take a reverse slice.
Slicing is covered by the introduction to the tutorial.
Leland made a great and detailed explanation about iterators. I would just show a brief practical demonstration showing in a different way that iterators get consumed / exhausted:
x = [2, 3, 5, 7]
y = reversed(x) # y is assigned an iterator over x in reversed order
y_list = list(y) # list y_list is created from y iterated till the end
print(y_list)
output:
[7, 5, 3, 2]
Letâs try to iterate the iterator y
again:
y_list2 = list(y)
print(y_list2) # but nooo...
The iterator y
was already consumed when we created the y_list
and we get no further items from it:
[]