Jan-21-2021, 03:52 PM
(This post was last modified: Jan-21-2021, 03:58 PM by InputOutput007.)
Hi guys,
I am learning python and I came across a weird thing which is hard for me to find the cause of it.
Here is my code:
Seriously, I don't know why the last number 2 is not taken into consideration to the next iteration of for-loop. Could anyone know the reason and may brighten up my mind, please?
[EDIT]
I added some comments to be printed and my idea is that after each iteration in which an element was removed, the length of the list is shorten, but the number of iteration is increasing and finally we have the length of a list equals 4 and the number of iteration is 4, so we cannot make any further iteration. Am I right? How could we fix that problem, does anybody have an idea?
I am learning python and I came across a weird thing which is hard for me to find the cause of it.
Here is my code:
1 2 3 4 5 6 7 |
l = [ 1 , 2 , 3 , 2 , 2 , 2 , 1 ] for el in l: print ( "element: " , el) if el = = 2 : l.remove(el) print ( "list after removing el == 2: " , l) print ( "list for the next iteration: " , l) |
[EDIT]
I added some comments to be printed and my idea is that after each iteration in which an element was removed, the length of the list is shorten, but the number of iteration is increasing and finally we have the length of a list equals 4 and the number of iteration is 4, so we cannot make any further iteration. Am I right? How could we fix that problem, does anybody have an idea?
1 2 3 4 5 6 7 8 9 10 |
l = [ 1 , 2 , 3 , 2 , 2 , 2 , 1 ] for el in l: print ( 'len list at the beginning of a new iteration: ' , len (l)) print ( "element: " , el) if el = = 2 : l.remove(el) print ( "list after removing el == 2: " , l) print ( 'len list strict after removing el == 2: ' , len (l)) print ( "list for the next iteration: " , l) print ( 'len list at the end of an iteration: ' , len (l)) |