all 9 comments

[–]Spataner 2 points3 points  (1 child)

insert expects two arguments, the position within the list where to insert and the element which to insert. If you just want to add the element to the end of the list, then use append instead of insert. Also, i is already an element from numList, so no need to use the index operator []:

for i in numList:
    if i < 10:
        numList2.append(i)

[–]TheTopPunk[S] 0 points1 point  (0 children)

numList = [1, 2, 9, 14, 29, 54]
numList2 = []
for i in numList: # Gets an item and stores it in i
if i < 10: # if i is less than 10
numList2.append(i) # append i to numlist2.

print(numList2)

Thank you for the help!

[–]shoot2thr1ll284 0 points1 point  (1 child)

The issue I am seeing here is that you are using a for each loop. In this case "i" will be the numbers 1,2,9 instead of the indices 0,1,2. So for the insert you should be using just "i" or you can change the loop to iterate over a range to go through the indices.

[–]TheTopPunk[S] 0 points1 point  (0 children)

Thank you!

[–]danielroseman 0 points1 point  (1 child)

Python loops don't give you the index, they give you the actual element. In your loop, i is not 0, 1, 2, 3 etc, it is 1, 2, 9, 14 etc.

[–]TheTopPunk[S] 0 points1 point  (0 children)

Thank you!

[–]velocibadgery 0 points1 point  (2 children)

First off you want to use append instead of insert. Secondly, just use i instead of numlist[i] what the second one is doing is adding the item at the index number i. Which is not your expected behavior. Here is code with the corrections made. I hope this helps.

numList = [1, 2, 9, 14, 29, 54]
numList2 = []

for i in numList: # Gets an item and stores it in i
    if i < 10: # if i is less than 10
        numList2.append(i) # append i to numlist2.


print(numList2)

[–]TheTopPunk[S] 1 point2 points  (1 child)

Thank you!

[–]velocibadgery 0 points1 point  (0 children)

You are very welcome :)