Skip to content Skip to sidebar Skip to footer

Python "reversed" Function Return Object With 'list' Function Doesn't Work Well

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 &l

Solution 1:

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]

Solution 2:

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.

Post a Comment for "Python "reversed" Function Return Object With 'list' Function Doesn't Work Well"