Do Python for loops work by reference?

前端 未结 2 642
梦如初夏
梦如初夏 2020-11-27 06:58

When using a for loop in Python to iterate over items in a list, will changing item (below) change the corresponding item in items?

2条回答
  •  死守一世寂寞
    2020-11-27 07:32

    Well, it really depends on the items.

    Take the following case:

    class test():
        pass
    
    a = test()
    a.value = 1
    
    b = test()
    b.value = 2
    
    l = [a,b]
    
    for item in l:
        item.value += 1
    
    for item in l:
        print item.value
    
    >>> 
    2
    3
    

    and in this case:

    l2 = [1,2,3]
    
    for item in l2:
        item += 1
    
    for item in l2:
        print item
    
    >>> 
    1
    2
    3
    

    So as you can see, you need to understand the pointers as Martijn said.

提交回复
热议问题