Python Forum
.remove() from a list - request for explanation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
.remove() from a list - request for explanation
#1
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:
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)
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?
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))
Reply


Messages In This Thread
.remove() from a list - request for explanation - by InputOutput007 - Jan-21-2021, 03:52 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Explanation of code ejKDE 4 389 Feb-26-2024, 02:50 PM
Last Post: ejKDE
  unable to remove all elements from list based on a condition sg_python 3 442 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 1,332 Nov-13-2022, 01:27 AM
Last Post: menator01
  A better explanation of the last post Led_Zeppelin 9 2,383 Sep-20-2022, 05:08 PM
Last Post: deanhystad
  Remove empty keys in a python list python_student 7 3,033 Jan-12-2022, 10:23 PM
Last Post: python_student
  Remove an item from a list contained in another item in python CompleteNewb 19 5,735 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  how can I correct the Bad Request error on my curl request tomtom 8 5,071 Oct-03-2021, 06:32 AM
Last Post: tomtom
  How to pass list of values to a API request URL chetansaip99 0 3,527 Sep-28-2021, 07:37 AM
Last Post: chetansaip99
  Operator meaning explanation Sherine 3 2,041 Jul-31-2021, 11:05 AM
Last Post: Sherine
  Explanation of except ... as : Fernando_7obink 2 1,930 Feb-13-2021, 04:45 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020