Reputation: 1975
I am trying to insert a number into a list of a sequence of numbers, for some reason this small program just sits there consuming CPU power... no idea why it's not working:
number = 5
lst = [4,5,6]
if all(x > number for x in lst):
lst.insert(0,number)
elif all(x < number for x in lst):
lst.append(number)
else:
for i,v in enumerate(lst):
if v>number:
lst.insert(i-1,number)
print (lst)
expected output:
lst = [4,5,5,6]
Upvotes: 0
Views: 2127
Reputation: 798
Your for loop is inserting the number 5 into the middle of the list a theoretically infinite amount of times (or until you run out of whatever limited resource the list consumes, whichever happens first).
1) for i,v in enumerate(lst):
2) if v>number:
3) lst.insert(i-1,number)
On the first pass, line 1 starts the loop with v = 4 and i = 0. Line 2 finds v is not greater than number.
On the second pass, line 1 continues the loop with v = 5 and i = 1. Line 2 is also false.
Third pass, line 1: v = 6, i = 2. Line 2 finds a true statement and moves to line 3. Line 3 inserts the object referenced by number into position i - 1, inserting 5 into position 1 of the list.
At this point the list is:
lst = [4, *5*, **5**, 6]
The italicized 5 is the number you added to the list. The bolded 5 is where the current pointer is, i = 2. Notice that the 6 we just checked got moved forward with the insert.
Fourth pass: v = 6, i = 3. Line 2 finds a true statement and moves to line 3. Line 3 inserts the object referenced by number into position i - 1, inserting 5 into position 2 of the list.
At this point the list is:
lst = [4, 5, *5*, **5**, 6]
etc etc etc.
A quick fix:
for i, v in enumerate(lst):
if v > number:
lst.insert(i-1, number)
**break**
You're just checking for and adding a single number, so break out of the loop once you insert it, since you're done.
Upvotes: 2