Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the length of reversed list

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?

like image 828
taesu Avatar asked Aug 26 '15 13:08

taesu


3 Answers

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.

like image 123
michaf Avatar answered Sep 29 '22 02:09

michaf


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

like image 28
Sergius Avatar answered Sep 29 '22 03:09

Sergius


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.

like image 20
Maksym Polshcha Avatar answered Sep 29 '22 02:09

Maksym Polshcha