def delete_starting_evens(lst):
for evens in lst:
if lst[0] % 2 ==0:
del lst[0]
return lst
print(delete_starting_evens([4, 8, 10]))
This should output []
but instead it outputs [10]
I am looking for comprehensive explanation :)
CodePudding user response:
After removing first element for loop will point to 2nd position which is 10 after deleting see below..
After removing second element for loop will point to 3rd position in the list but there is no 3rd position left in the list hence if condition will not run and directly it print 10
You can see another example if you take [10,12,14,18]
your output will be [14,18]
..
reason
after 1st deletion list becomes [12,14,18]
now for loop will point to 14
after 2nd deletion list becomes [14,18]
now for loop will point outside the list hence it directly ends for loop and return [14,18]
Conclusion:- for loop will iterate sequentially. not like after deleting it check from the first position..!
CodePudding user response:
Iterating over a list while removing data is a very bad idea, it will create problems like you experience. Try this in stead:
def delete_starting_evens(lst: list):
tmp = []
for evens in lst:
if not evens % 2 == 0:
tmp.append(evens)
return tmp
print(delete_starting_evens([4, 8, 9, 10]))
Result:
[9]
I added a 9 to the list for testing purposes.
CodePudding user response:
The problem is in for loop.
intially the elements where [4,8,10]
even variable in loop was pointing to 4
after one loop the elemennts are [8,10]
now the even variable would be pointing in 2nd element i.e 10 and the last element
during second execution 8 is removed only values left in list is [10]
as our even variable was pointing to 2nd element i.e last elemnt of list so next execution won't take place,
and we are left with [10] in list.
I hope you must have got it.
CodePudding user response:
This is because list is mutable and the changes made is being directly reflected in the for loop
When you start the program the value of lst: [4 ,8, 10]
The for-loop here is in such a way that each time it iterates it take the next value from the list, means for first iteration it takes the first element of lst and for second iteration it takes second element
So in the first Iteration:
Value of lst: [4, 8, 10]
Value of evens: 4
Element at index 0: 4
Since element at index 0 is divisible by 2 it deletes the element at index 0
Value of lst becomes: [8, 10]
So now in the second iteration
Value of lst: [8, 10]
Value of evens: Now as first iteration is done the for-loop takes the second element of the list lst => 10
Element at index 0: 8
Now also the element at index 0 is divisible by 2, so it deletes the element at index 0
Value of list becomes: [10]
Now the for loop terminates here and returns the list
Thats why it shows the output as [10]