Reputation: 13
When i use 'reversed' function return object with 'list' function to make list, it remove their element.
>>> a = [1,2,3,4,5]
>>> b = reversed(a)
>>> b
<list_reverseiterator object at 0x000001D9059A6438>
>>> c = list(b)
>>> c
[5, 4, 3, 2, 1]
>>> c
[5, 4, 3, 2, 1]
>>> list(b)
[]
Second 'list(b)' remover their data, so that i cannot use it data again. Why this issue happened?
Upvotes: 0
Views: 2334
Reputation: 781058
As you can see in your first output, reversed()
returns an iterator, not a new list. That's why you need to call list(b)
to get an actual list.
Most iterators can only be used once.*
Every time you fetch a value from an iterator, it updates its internal state to remember the current position, so that the next fetch can get the next value, and so on. Once you get to the end, there's nothing else to fetch.
When you use list(b)
, the list()
function goes into a loop, fetching all the values from the b
iterator. When it's done, the iterator is at the end of its data. If you try to use it again, there's nothing left to fetch. There's no way to reset it back to the beginning.
*An exception is when you use a file
object as an iterator. Instead of the iterator maintaining its own state, it uses the state of the file
object, and just performs a readline()
call from the current file position. So you can use file.seek(0)
to reset the iterator to the beginning of the file.
Upvotes: 1
Reputation: 155418
reversed
returns a reverse iterator (can only be read once), not a reversed sequence (can be used repeatedly). If you want to make a repeatably usable reversed version of an arbitrary sequence, either immediately convert to list
(so you don't see the intermediate iterator):
>>> a = [1,2,3,4,5]
>>> b = list(reversed(a))
or use the reversing slice (which also preserves the type of the original sequence):
>>> a = [1,2,3,4,5]
>>> b = a[::-1]
Upvotes: 3