Gang Fang
Gang Fang

Reputation: 857

Using python list comprehension to modify the list itself, unexpected result?

I tried to make a change to each element in a list A in place and have two methods: use_list_comprehension(A, length) and use_plain_loop(A, length). The two perform the same operation on elements but generate different results.

My question is: does python list comprehension first make a copy of A, then use that copy as the source to get elements and perform operations on them?

def arrange(A):
    length = len(A)
    A = use_list_comprehension(A, length) # we get [19, 20, 12, 1, 8]

    # A = use_plain_loop(A, length) # we get [19, 95, 12, 476, 2383]
    return A        


def use_list_comprehension(A, length):
    return [ A[i]+A[A[i]]*length for i in range(length) ]


def use_plain_loop(A, length):
    for i in range(length):
        A[i] += A[A[i]]*length
    return A


print(arrange([4,0,2,1,3]))

Upvotes: 0

Views: 146

Answers (1)

Jacob Rodal
Jacob Rodal

Reputation: 650

No, the list comprehension is not making a copy of A, it's making a new list where the value stored in index i of that list is A[i]+A[A[i]]*length. Thus, use_list_comprehension(A, length) returns a new list and then A is set to that new list in line 3. use_plain_loop(A, length), on the other hand, actually modifies the list in place, as A[i] += A[A[i]]*length replaces the value stored at A[i] with A[i] + A[A[i]]*length.

Upvotes: 2

Related Questions