[Python] Deleting an element of a list in a for loop and reassigning the list [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to break a list to 2 folds at a time (for 10 times) and perform an operation on each of the partitions. I want to perform this operation on the list with a ratio of 1:9 at a time. Meaning that I have divided the list to 10 folds and in the first iteration I will perform the operation on the first fold and the remaining 9, in the second iteration I will perform it on the second fold and the remaining 9 and so on.

    To do this I decided to keep a copy of the original list and assign one of the folds to a temporary variable, delete it from the list and get the remainder as the second partition. And then reassign the copy of the list to it for the next iteration.

    However, it seems that the copy and the original are always the same throughout the for loop and thus I get a index out of range error. Here is a simple example of the problem:

    >>> a = ['a', 'b', 'c', 'd', 'e', 'f']
    >>> b = a
    >>> b
    ['a', 'b', 'c', 'd', 'e', 'f']
    >>> for i in xrange (len(a)):
    del (b )
    b = a

    Traceback (most recent call last):
    File "<pyshell#22>", line 2, in <module>
    del (b )
    IndexError: list assignment index out of range


    It seems that both a and b point to same location in memory and there is only one location that stores the actual content of the list. Could you tell me what is the problem here and how I can solve it?

    Continue reading...

Compartilhe esta Página