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?
You can use time.sleep
import time
for i in l:
print i
time.sleep(1)
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
You can pause the code execution using time.sleep
:
import time
for i in l:
print(i)
time.sleep(1)
Use the time.sleep
function. Just do time.sleep(1)
in your function.
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