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
#3
Internally, Python lists are integer indexed dynamic arrays. Here is an interesting, if old, question and interesting answers and links on stackoverflow.

There is quite a lot going on behind the scenes when you add or delete elements!

As I understand it, you cannot access the values in a list without using the pointer variables, the index, which tells us where they are in memory and what kind of value is stored there.

So, if my_list.remove(3) seems to get rid of 3 without using its index, that is only superficially so.

I don't know how .remove() works internally, but you can fake it like this:

def remove_it(val, alist):
    for i in range(len(alist)):
        if alist[i] == val:
            alist.pop(i)
            return alist

my_list = [1, 2, 3, 4, 5]
remove_it(3, my_list)
Output:
[1, 2, 4, 5]
Or like this:

def remove_it(val, alist):
    for i in range(len(alist)):
        if alist[i] == val:
            del alist[i]
            return alist

my_list = [1, 2, 3, 4, 5]
remove_it(3, my_list)
Output:
[1, 2, 4, 5]
Reply


Messages In This Thread
RE: removing one list element without using its index - by Pedroski55 - Feb-21-2025, 05:59 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,337 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,212 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,467 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,635 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