Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: argument to reversed() must be a sequence

How come enumerate does not produce a sequence?

----> 1 BytesInt('1B')

     12 def BytesInt(s):
     13     suffixes = ['B','KB','MB','GB','TB','PB','EB','ZB','YB']
---> 14     for power,suffix in reversed(enumerate(suffixes)):
     15         if s.endswith(suffix):
     16             return int(s.rstrip(suffix))*1024**power

TypeError: argument to reversed() must be a sequence
like image 807
ArekBulski Avatar asked Dec 19 '22 21:12

ArekBulski


2 Answers

enumerate indeed does not return a sequence, it is a generator. If your input is relatively small you can convert it to a list:

for power, suffix in reversed(list(enumerate(suffixes))):
like image 188
Daniel Roseman Avatar answered Jan 05 '23 23:01

Daniel Roseman


enumerate() produces an iterator, not a sequence. A sequence is addressable (can be subscribed with any index), while an iterator is not.

Either don't use enumerate(), subtract from len(suffixes) or convert the enumerate() output to a list.

Subtraction gives you the advantage of avoiding materialising a list:

for index, suffix in enumerate(reversed(suffixes), 1):
    power = len(suffixes) - index

Demo:

>>> def BytesInt(s):
...     suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
...     for index, suffix in enumerate(reversed(suffixes), 1):
...         power = len(suffixes) - index
...         if s.endswith(suffix):
...             return int(s.rstrip(suffix)) * 1024 ** power
...
>>> BytesInt('1B')
1
>>> BytesInt('1KB')
1024
>>> BytesInt('1TB')
1099511627776
like image 34
Martijn Pieters Avatar answered Jan 05 '23 21:01

Martijn Pieters