Hi everyone,
While I was studying I was doing an assignment that was about removing a value from a list.
But when it comes to a value that appears multiple times in a list, I tried to remove it with a for loop, which is actually not the right way of doing it because it wil cause to skip values because of the changing index.
my question is:
Do I understand the way this iteration / for loop works?
Let me show you my example.
#Remove all list items with value = 1
numbers = [1,1,5,6,56,1]
for x in numbers:
if x == 1:
numbers.remove(1)
print(number)
#Output: [5, 6, 56, 1]
What is actually happening?
Start
[1, 1, 5, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index
Iteration 1
Value on index 0 removed because it has value = 1
[1, 5, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index
Iteration 2
For loop already did index 0 so it will skip the number 1, now next is index 1. 5 is not 1 so it will move to the left. Same for 6 and 56.
From
[1, 5, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # IndexTo
[5, 1, 6, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index
Iteration 3
[5, 6, 1, 56, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index
Iteration 4
[5, 6, 56, 1, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index
Iteration 5
The value on index 4 is a 1 which will be removed.
[5, 6, 56, 1, 1] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index
This is the end of the for loop.
The number 1 on the end of the list stays because it was skipped in the for loop, because the index 0 was already iterated.
[5, 6, 56, 1,] # Values
[0, 1, 2 ,3 ,4 , 5 ] # Index (index 5 does not exist anymore)