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
#3
Don't modify an iterator while you're iterating over it. Some options are to loop over a copy of the list or to just copy the data you do want rather than delete the data you don't.

l = [1, 2, 3, 2, 2, 2, 1]
    for el in l[:]:  # loops over a copy of l.  Modifying l doesn't change the loop iterator.
    ...
l = [1, 2, 3, 2, 2, 2, 1]
l = [e for e in if l != 2]  # list comprehension copies the data we want directly
InputOutput007 likes this post
Reply


Messages In This Thread
RE: .remove() from a list - request for explanation - by bowlofred - Jan-21-2021, 04:43 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  remove duplicates from dicts with list values wardancer84 27 1,053 May-27-2024, 04:54 PM
Last Post: wardancer84
  Explanation of code ejKDE 4 568 Feb-26-2024, 02:50 PM
Last Post: ejKDE
  unable to remove all elements from list based on a condition sg_python 3 610 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 1,546 Nov-13-2022, 01:27 AM
Last Post: menator01
  A better explanation of the last post Led_Zeppelin 9 2,609 Sep-20-2022, 05:08 PM
Last Post: deanhystad
  Remove empty keys in a python list python_student 7 3,315 Jan-12-2022, 10:23 PM
Last Post: python_student
  Remove an item from a list contained in another item in python CompleteNewb 19 6,133 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  how can I correct the Bad Request error on my curl request tomtom 8 5,345 Oct-03-2021, 06:32 AM
Last Post: tomtom
  How to pass list of values to a API request URL chetansaip99 0 3,614 Sep-28-2021, 07:37 AM
Last Post: chetansaip99
  Operator meaning explanation Sherine 3 2,163 Jul-31-2021, 11:05 AM
Last Post: Sherine

Forum Jump:

User Panel Messages

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