how to loop down in python list?
for example
loop:
L = [1,2,3]
for item in L
print item #-->1,2,3
loop down:
L = [1,2,3]
for ???
print item #-->3,2,1
thank you
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
A for loop can also count backwards, so long as we can define the right conditions. In order to count backwards by twos, we'll need to change our initialization, condition, and final-expression.
Batteries included.
for i in reversed([1, 2, 3]):
print i
Slicing the list (ls[::-1]
) is great for making a reversed copy, but on my machine it's slower for iteration, even if the list is already in memory:
>>> def sliceit(x):
... l = range(x)
... for i in l[::-1]:
... i
...
>>> def reverseit(x):
... l = range(x)
... for i in reversed(l):
... i
...
>>> %timeit sliceit(100)
100000 loops, best of 3: 4.04 µs per loop
>>> %timeit reverseit(100)
100000 loops, best of 3: 3.79 µs per loop
>>> %timeit sliceit(1000)
10000 loops, best of 3: 34.9 µs per loop
>>> %timeit reverseit(1000)
10000 loops, best of 3: 32.5 µs per loop
>>> %timeit sliceit(10000)
1000 loops, best of 3: 364 µs per loop
>>> %timeit reverseit(10000)
1000 loops, best of 3: 331 µs per loop
As is often true in cases like these, the difference is pretty negligible. It might be different for different versions of Python (I used Python 2.7 for the above test). The real benefit of using reversed
is readability -- it would be preferable in most cases even if it cost a couple of extra microseconds.
Reverse the sequence.
L = [1,2,3]
for item in reversed(L)
print item #-->3,2,1
Another solution:
for item in L[::-1]:
print item
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