Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'backwards' enumerate

Tags:

python

Is there a way to get a generator/iterator that yields the reverse of enumerate:

from itertools import izip, count

enumerate(I) # -> (indx, v)
izip(I, count()) # -> (v, indx)

without pulling in itertools?

like image 212
tacaswell Avatar asked Nov 28 '22 21:11

tacaswell


2 Answers

You can do this with a simple generator expression:

((v, i) for i, v in enumerate(some_iterable))

Here as a list comprehension to easily see the output:

>>> [(v, i) for i, v in enumerate(["A", "B", "C"])]
[('A', 0), ('B', 1), ('C', 2)]
like image 71
Gareth Latty Avatar answered Dec 06 '22 14:12

Gareth Latty


((v, indx) for indx, v in enumerate(I))

if you really want to avoid itertools. Why would you?

like image 38
Elmar Peise Avatar answered Dec 06 '22 14:12

Elmar Peise