Home > Mobile >  Try to append an integer to a list in a For Loop with If condition
Try to append an integer to a list in a For Loop with If condition

Time:01-09

I try to append integers that are over 10 (which is 13 in this case) to MyList with the following code, but an error occurred.

MyList = [2,2,2,7,13]
for i in MyList:
    if i >= 10:
        MyList.append(i)

print(MyList)

KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-4-b61d86f65af6> in <module>
      2 for i in MyList:
      3     if i >= 10:
----> 4         MyList.append(i)
      5 
      6 MyList

If I use append as the following, it works. Can someone tell me the difference?

MyList = [2,2,2,7,13]
for i in range(len(MyList)):
    if MyList[i] >= 10:
        MyList.append(MyList[i])

print(MyList)
[2, 2, 2, 7, 13, 13]

CodePudding user response:

The first example doesn't work because it gets stuck in an infinite loop. You keep appending to that list you're traversing. If you were to print it out at any point, it'd look like this [2,2,2,7,13,13,13,13,13,13,13.....]

In the second example, you're determining the size of the list at the very beginning (using the len function) and that doesn't get updated once you update the array because it was already computed.

CodePudding user response:

Hello and welcome to StackOverflow,

In the upper code, you are constantly adding new values to the list, so that your for loop never finishes.

In the example below, you get the length of the list first and only loop len(MyList) times, not infinite.

CodePudding user response:

in following code you are adding the numbers in MyList and keep iterating over that only.

MyList = [2,2,2,7,13]
for i in MyList:
    if i >= 10:
        MyList.append(i)
print(MyList)

but in following you are iterating only the list size times. which have a limit.

MyList = [2,2,2,7,13]
for i in range(len(MyList)):
    if MyList[i] >= 10:
        MyList.append(MyList[i])

CodePudding user response:

You are adding items to MyList while iterating over it, causing an infinite loop in this case. A solution would be creating another list and merging the lists after the loop:

MyList = [2,2,2,7,13]
toAdd = []
for i in MyList:
    if i >= 10:
        toAdd.append(i)

MyList  = toAdd

print(MyList)
  •  Tags:  
  • Related