A.Lee
A.Lee

Reputation: 265

what is difference using unpack in for loop and not in python

Can anyone explain to me why on test1, nums is [[0,0],[-1,-1],[0,0],[0,0]] but not on test2? as my understand python for xx in xxx is pretty much like for loop in any other language and take element by element. So what is different between using unpack in for loop and not? Thank you

test([[0,0],[0,0],[0,0],[0,0]])
test2([[0,0],[0,0],[0,0],[0,0]])
def test1(self, nums):
    ctn = 0
    for e in nums:
        ctn += 1
        u, v = e
        if ctn == 2:
            e[0] = e[1] = -1
    print(nums)  #[[0,0],[-1,-1],[0,0],[0,0]]

def test2(self, nums):
    ctn = 0
    for u, v in nums:
        ctn += 1
        if ctn == 2:
            u = v = -1
    print(nums)  #[[0,0],[0,0],[0,0],[0,0]]

Upvotes: 2

Views: 86

Answers (4)

Serge Ballesta
Serge Ballesta

Reputation: 148965

Variable hold references in Python. That means that when you assign a mutable object (a list is) to a variable and change the object through that variable you change the original object. That is the reason why test1 does change the original list.

But when you assign to a variable, you do not change the object it previously refered, but only have it point to a new object. As you assign to u and v in test2 you change nothing in the original objects.


When you use e[0] = -1, you do not assign to variable e but actually modify the object pointed to by e

Upvotes: 1

Tom.chen.kang
Tom.chen.kang

Reputation: 183

in the first function u, v =e do nothing,delete it i get the same answer

def test1(nums):
    ctn = 0
    k = []
    for e in nums:
        ctn += 1
        if ctn == 2:
            e[0] = e[1] = -1
    print(nums)

def test2(nums):
    ctn = 0
    for u, v in nums:
        ctn += 1
        if ctn == 2:
            u = v = -1
    print(nums)

Upvotes: 0

Dillon Davis
Dillon Davis

Reputation: 7750

The variables u and v are references to the elements in the sublist, without any reference to the sublist itself. When you change either value, it does not cause any side effects.

However, e is a reference to the sublist itself. When you index into e and change its values, you are performing an assignment in the sublist itself, and thus causes side effects (changing the value in the original list).

Upvotes: 2

Paul M.
Paul M.

Reputation: 10799

In test2, u and v are temporary copies of the original values in the list. Because they are copies, any changes you make to them will not be reflected in the original list.

Upvotes: -1

Related Questions