0

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?

1

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your comment. It's really useful
1

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.

1 Comment

Thank you for your comment. Also, thank you for widening my sight~!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.