How can I slow down the loop in 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 next for loop so that the next item in the list prints only 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?

+7
source share
5 answers

You can use time.sleep

 import time for i in l: print i time.sleep(1) 
+13
source

If you use time.sleep(1) , your loops will run a little more than a second, since loops and printing also take some time. The best way is to sleep for the remainder of the second. You can calculate that with -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 ... 

This is easy to see 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 

against

 >>> 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 
+9
source

You can pause code execution using time.sleep :

 import time for i in l: print(i) time.sleep(1) 
+5
source

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

+3
source

Use time.sleep(number) :

 for i in range(i) print(1) time.sleep(0.05) 
-4
source

All Articles