'How to skip an iteration of a loop after some time in Python?
I have a code with a loop that I need to skip an iteration if it is taking too much time.
Example:
list = ['a', 'b', 'c', ......]
for x in list:
#do something that takes time
In my code, the list has several paths. I loop through every path of that list to do some actions in files, but there are some files that take too long. I don't want the script to be stuck in a path for more than half an hour... If it takes more than 30 minutes while executing it, I want it to skip that path and go to the next on the list.
Solution 1:[1]
I assume you mean that you want to break out of the loop if a certain amount of time has elapsed. If so, take a look at the time module. You can use features from there to note the time before you enter the loop then, at appropriate points in the code, compare the elapsed time from your initial record of the start time and continue accordingly
Solution 2:[2]
I've came up with this solution:
import time
start_time = time.time()
#a lot of code in the middle
print(start_time)
list=['1', '2', '3', '4']
for i in list:
start_time = time.time()
while True:
print("hello world {}".format(i))
current_time = time.time()
elapsed_time = current_time - start_time
print(elapsed_time)
if elapsed_time > 3: #test for 3seconds
print("More than {} seconds".format(elapsed_time))
del elapsed_time
break
print("exited the loop")
Solution 3:[3]
You might like this code
import pprint as p
llist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
HashMap = {}
for i, x in enumerate(llist):
HashMap[x] = i
# Your condition
if len(HashMap) > 20:
break # You can do continue
p.pprint(HashMap, width = 200, sort_dicts = False)
Explanation
Imported pprint to print beautifully
changed the var name from list to llist because I don't want to mask built-ins
Created a dictionary HashMap to store the index of the items and the items
looped on llist using enumerate() to get those indices
After loop first step was to append the item to HashMap so that we keep the count
Then the condition will come.....
Then checking length of HashMap, if it exceed the condition then break
Finally to print it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Albert Winestein |
| Solution 2 | Catarina Ribeiro |
| Solution 3 |
