Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I slow down a loop in Python?

Tags:

python

If I have a list l:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Is there a way to control the following for loop so that the next element in the list is only printed one second after the previous?

for i in l:
    print i

In other words, is there a way to elegantly slow down a loop in Python?

like image 513
mpjan Avatar asked May 15 '13 00:05

mpjan


4 Answers

You can use time.sleep

import time

for i in l:
    print i
    time.sleep(1)
like image 127
karthikr Avatar answered Oct 25 '22 04:10

karthikr


If you use time.sleep(1), your loops will run a little over a second since the looping and printing also takes some time. A better way is to sleep for the remainder of the second. You can calculate that by using -time.time()%1

>>> import time
>>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in L:
...     time.sleep(-time.time()%1)
...     print i
... 

It's easy to observe this by using print i, repr(time.time())

>>> for i in L:
...     time.sleep(-time.time()%1)
...     print i, repr(time.time())
... 
0 1368580358.000628
1 1368580359.001082
2 1368580360.001083
3 1368580361.001095
4 1368580362.001149
5 1368580363.001085
6 1368580364.001089
7 1368580365.001086
8 1368580366.001086
9 1368580367.001085

vs

>>> for i in L:
...     time.sleep(1)
...     print i, repr(time.time())
... 
0 1368580334.104903
1 1368580335.106048
2 1368580336.106716
3 1368580337.107863
4 1368580338.109007
5 1368580339.110152
6 1368580340.111301
7 1368580341.112447
8 1368580342.113591
9 1368580343.114737
like image 22
John La Rooy Avatar answered Oct 25 '22 06:10

John La Rooy


You can pause the code execution using time.sleep:

import time

for i in l:
    print(i)
    time.sleep(1)
like image 35
poke Avatar answered Oct 25 '22 05:10

poke


Use the time.sleep function. Just do time.sleep(1) in your function.

like image 34
BrenBarn Avatar answered Oct 25 '22 06:10

BrenBarn