0

I'm trying to delete every instance of a class in a for loop. However, there is a point in which the list length meets the for loop iteration. See:

    for n in range(len(myList)):
        print(len(myList), n)
        del myList[n]

Output:

15 0
14 1
13 2
12 3
11 4
10 5
9 6
8 7
7 8
IndexError: list assignment index out of range`

The only solution that came across my head so far was to create a variable for each item in the list and deleting them that way, but I've heard that's usually not something you need to do. Any ideas on how I can achieve this?

Zesty Dragon
  • 551
  • 3
  • 18
pigaroos
  • 53
  • 5
  • `while myList: myList.pop(0)`? But it's not really clear what you are doing this rather than just assigning an empty list to `myList`. – Mark May 26 '20 at 00:31
  • You're looking for `for n in reversed(range(len(myList))):`, but that's not very pythonic. Instead, you should probably use `for n, item in enumerate(myList):` (or, if you don't need the index, just use `for item in myList:`) – Holden Rohrer May 26 '20 at 00:32
  • @Mark Meyer This list contains references to instances of classes. If I wanted to assign an empty list to `myList`, then I think I'd use ```.clear()``` – pigaroos May 26 '20 at 00:34
  • 1
    What does references to classes have to do with anything? – Mark May 26 '20 at 00:35
  • I'm trying to delete them, and I can't do that just by clearing them off the list because they have references to each other. – pigaroos May 26 '20 at 00:37
  • 1
    `del` doesn't delete objects. There is no way to delete objects manually in Python. – user2357112 May 26 '20 at 00:39
  • 1
    Don't worry about circular references. The garbage collector will handle those. – user2357112 May 26 '20 at 00:39
  • @user2357 Thank you for clarifying. However, I seem to reach the recursion limit before it gets collected... [This answer](https://stackoverflow.com/a/16687693/11228943) states that the garbage collector is not guaranteed to collect circular references. Could this be the case? – pigaroos May 26 '20 at 00:56
  • 1
    If you're hitting the recursion limit, that has nothing to do with memory reclamation. – user2357112 May 26 '20 at 01:20
  • Sorry for not being clear, I meant that I hit the recursion limit because the garbage collector didn't seem get rid of the class instances which call each other's functions, leading to the limit – pigaroos May 26 '20 at 01:23
  • 1
    This description is ambiguous and doesn't give us enough to go on. If you're having an infinite recursion bug, post a question about the bug, with a [mcve] so we can actually debug it. – user2357112 May 26 '20 at 01:26

1 Answers1

0

One way is to step through the list backwards.

for n in range (len (myList) -1, -1, -1):
bashBedlam
  • 1,402
  • 1
  • 7
  • 11