I have a list with such structure:
[(key1, val1), (key2, val2), ...]
And I want to iterate over it getting key and the index of item on each step. In reverse order.
Right now I'm doing it like this:
for index, key in reversed(list(enumerate(map(lambda x: x[0], data)))):
print index, key
It works perfectly, but I'm just worrying if it's a properly way to do. Can there is be a better solution?
Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.
We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.
3) Using for loop Another way to reverse the python list without the use of any built-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed.
But Python does have a built-in reversed function. If you wrap range() inside reversed() , then you can print the integers in reverse order. range() makes it possible to iterate over a decrementing sequence of numbers, whereas reversed() is generally used to loop over a sequence in reverse order.
enumerate()
cannot count down, only up. Use a itertools.count()
object instead:
from itertools import izip, count
for index, item in izip(count(len(data) - 1, -1), reversed(data)):
This produces a count starting at the length (minus 1), then counting down as you go along the reversed sequence.
Demo:
>>> from itertools import izip, count
>>> data = ('spam', 'ham', 'eggs', 'monty')
>>> for index, item in izip(count(len(data) - 1, -1), reversed(data)):
... print index, item
...
3 monty
2 eggs
1 ham
0 spam
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