Python Forum
removing one list element without using its index
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
removing one list element without using its index
#4
Your code example is wrong.
  • Indentation of return
  • the use of range(len(element)), iterate directly
  • alist is modified in-place and is also returned
  • Iterating over a list and modifying the list in-place will throw an IndexError.

If you change then indentation to iterate over all elements, then you would get an IndexError.

This modifies the list in-place and does return None:
def remove_it(val, alist):
    remove = []

    for index, element in enumerate(alist):
        if element == val:
            remove.append(index)
    
    for index in reversed(remove):
        alist.pop(index)


my_list = [3, 1, 2, 3, 4, 5, 3]

print(my_list)
remove_it(3, my_list)
print(my_list)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: removing one list element without using its index - by DeaD_EyE - Feb-21-2025, 09:25 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  question about changing the string value of a list element jacksfrustration 4 2,323 Feb-08-2025, 07:43 AM
Last Post: jacksfrustration
  extract an element of a list into a string alexs 5 4,335 Aug-30-2024, 09:24 PM
Last Post: alexs
  element in list detection problem jacksfrustration 5 2,025 Apr-11-2024, 05:44 PM
Last Post: deanhystad
  Variable for the value element in the index function?? Learner1 8 3,211 Jan-20-2024, 09:20 PM
Last Post: Learner1
  list in dicitonary element problem jacksfrustration 3 1,806 Oct-14-2023, 03:37 PM
Last Post: deanhystad
Thumbs Down I hate "List index out of range" Melen 20 10,465 May-14-2023, 06:43 AM
Last Post: deanhystad
  Find (each) element from a list in a file tester_V 3 2,329 Nov-15-2022, 08:40 PM
Last Post: tester_V
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 3,628 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  IndexError: list index out of range dolac 4 3,542 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 2,094 Jul-01-2022, 10:52 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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