0

I am in python and iterating through list of class objects, removing certain ones that don't fit certain parameters. When called the list.remove() function it removes the last index instead of the parsed one. The specific code as follows:

for k in tile_to_print:
    x_thing = int(x_size / 2) + k.x - player_position[0]
        if x_thing > x_size - 1:
        tile_to_print.remove(k)

How would I change this to remove a parsed object instead of the last.

  • 2
    You are removing elements while iterating, this changes the size of the list and causes the iteration to fail – mozway Apr 09 '22 at 04:45

1 Answers1

1

Note that the remove() method doesn't take the index of the item to be removed as an argument, instead it takes the value you want to remove.

Example:

my_list = [1, 0, 2, 3]
my_list.remove(1)
print(my_list) # [0, 2, 3]

If you want to remove an item from its index, you can use pop():

my_list = [1, 0, 2, 3]
my_list.pop(1)
print(my_list) # [1, 2, 3]
Gabriel Caldas
  • 371
  • 2
  • 13
  • There are no repeats in this list as both tested by the code and manually. There is only one "k" that it could reference. I have tried referencing it directly with no luck. Would I need to use the objects name to remove it specifically? – Joseph Murray Apr 09 '22 at 04:43
  • Oh, I see no problem on your code then, when you call remove, it should remove the first matching element. Is there any other point that could be leading to this error? – Gabriel Caldas Apr 09 '22 at 04:49
  • Actually, the problem is as stated by @mozway, as you're removing items while iteraiting, it doesn't go as expected. You could use an auxiliary list to receive the values that must be kept from the original list while iterating. – Gabriel Caldas Apr 09 '22 at 04:53