(Yet Another) List Aliasing Conundrum

前端 未结 6 688
忘掉有多难
忘掉有多难 2020-12-10 18:37

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)
<         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 18:55

    Sometimes I find it easier to think in the less abstract world of C. In Python, think of every variable as being a pointer. When you do i = 0; i = 1, you're not doing this:

    int * i = malloc(sizeof(int));
    *i = 0;
    *i = 1;
    

    It's more like this:

    int * i = malloc(sizeof(int));
    *i = 0;
    free(i);
    i = malloc(sizeof(int));
    *i = 1;
    

    You're not changing the value, you're moving the pointer to a new value.

    With a list though, the l pointer stays the same, but you're updating the value at the specified index. Thus l = [0]; l[0] = 1 looks like:

    int * l[] = {0};
    l[0] = 1;
    

    (Note: I realize Python ints and lists are not really C ints and arrays, but for this purpose, they're similar.)

    Protip: "alias" is not a Python term, so please avoid it. "Reference" or just "variable" are better.

提交回复
热议问题