0

I wanted to make a program that deletes all the values less than 3 from a list

now ive created a list and want to delete all the numbers less than 3 from that list. and this is the program ive made to achieve it:

somelist=[1,3,5,3,65,67,4,3,2,2,4,56,6,4,3,4,5,4,8]
for x in somelist:
    if x<3:
        somelist.remove(x)
    print(x)

The output i got is:

1
5
3
65
67
4
3
2
4
56
6
4
3
4
5
4
8

It contains 1 & 2.. How's that possible?

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    Your print statement is inside the for loop. It prints all elements, what you should do is to print(somelist) outside the for loop. – Yassin Shanwany Aug 16 '23 at 14:18
  • Thank you. I got the desired output. But can you please elaborate on: 1. how one of the two 2s was removed? and 2. the print statement is after .remove then shouldnt the loop first remove all elements < 3 and then print the list? You help is appreciated but if you can elaborate on this, i'll be really thankful – Dipen Kadam Aug 16 '23 at 15:42
  • 1. When list.remove is executed it removes the element from the list but does not update the index of the loop. So it get skipped, same as for the first item in the list the output printed 1 then 5 isof 3. 2. Your print statement is printing the x (item of the list during tteration) not somelist. – Yassin Shanwany Aug 16 '23 at 16:54

0 Answers0