Getting the length of reversed list doesn't work:
lst = [1,2,3]
lst = reversed(lst)
print len(lst)
throws TypeError: object of type 'listreverseiterator' has no len()
A work around is:
lst = [1,2,3]
lst_length = len(lst)
lst = reversed(lst)
print lst_length
# OR
lst = lst[::-1]
print len(lst)
Now my real question is why?
Simply reversing a list does not alter the length of the list,
so why is Python throwing that exception?
The function reversed() returns an iterator, not an actual list. You cannot directly get the len() of an iterator (see here). You could instead reverse the list using Extended Slice syntax:
lst_reversed = lst[::-1]
or reverse the list in place:
lst.reverse()
If you must use an iterator you could first turn it into a list:
lst_reversed = list(reversed(lst))
With each of these approaches len() will then work as expected.
reversed doesn't produce new list, it just return iterator object. You can use lst.reverse() - and it doesn't return anything, but make your lst in reversed order
reversed
returns iterator so to determine length you have to consume it.
For example rev_len = len(list(reversed(lst)))
.
FYI list.reverse
method reverses a list in place: lst.reverse()
Anyway your reversed list has the same size as the original one, so you can just determine the length even before reversing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With