Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Yet Another) List Aliasing Conundrum

Tags:

python

I thought I had the whole list alias thing figured out, but then I came across this:

    l = [1, 2, 3, 4]
    for i in l:
        i = 0
    print(l)

which results in:

    [1, 2, 3, 4]

So far so good.

However, when I tried this:

    l = [[1, 2], [3, 4], [5, 6]]
    for i in l:
        i[0] = 0

I get

    [[0, 2], [0, 4], [0, 5]]

Why is this?

Does this have to do with how deep aliasing goes?

like image 677
Joel Cornett Avatar asked Jan 25 '12 03:01

Joel Cornett


1 Answers

The first rebinds the name. Rebinding a name changes only the local name. The second mutates the object. Mutating an object changes it everywhere it is referenced (since it's always the same object).

like image 125
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 03:11

Ignacio Vazquez-Abrams