Python Forum
I cannot delete and the elements from the list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I cannot delete and the elements from the list
#4
Don't modify an iterator while you're iterating over it,it's a known bad patternđź’€
Will mess up list index and will get your result.
Could add enumerate(l2[:]) to make it work,but still no t good as as remove() has to go over the whole list for every iteration O(n^2).

The solution is to make a new list,then therew is no remove()(that rarely ever need to be used) used in the loop.
l2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = 1
result = []
for ind, el in enumerate(l2):
    if el != a:
       result.append(el)

print(result)
[0, 2, 3, 4, 5, 6, 7, 8, 9]
Or list comprehension.
>>> l2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [el for el in l2 if el != 1]
[0, 2, 3, 4, 5, 6, 7, 8, 9]
quest likes this post
Reply


Messages In This Thread
RE: I cannot delete and the elements from the list - by snippsat - May-11-2021, 11:58 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 460 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 495 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Delete strings from a list to create a new only number list Dvdscot 8 1,556 May-01-2023, 09:06 PM
Last Post: deanhystad
  Checking if a string contains all or any elements of a list k1llcod3 1 1,117 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 2,011 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,170 May-17-2022, 11:38 AM
Last Post: Larz60+
  Why am I getting list elements < 0 ? Mark17 8 3,170 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 2,147 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Extracting Elements From A Website List knight2000 2 2,287 Jul-20-2021, 10:38 AM
Last Post: knight2000
  Make Groups with the List Elements quest 2 1,986 Jul-11-2021, 09:58 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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