Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop down in python list (countdown)

Tags:

python

loops

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

like image 848
nguyên Avatar asked Jul 08 '11 04:07

nguyên


People also ask

Can you loop a list in Python?

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.

Can a for loop count backwards?

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.


3 Answers

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.

like image 78
senderle Avatar answered Sep 23 '22 01:09

senderle


Reverse the sequence.

L = [1,2,3]
for item in reversed(L)
    print item #-->3,2,1
like image 24
Ignacio Vazquez-Abrams Avatar answered Sep 26 '22 01:09

Ignacio Vazquez-Abrams


Another solution:

for item in L[::-1]:
    print item
like image 44
Jacob Avatar answered Sep 24 '22 01:09

Jacob