Python List & for-each access (Find/Replace in built-in list)

前端 未结 3 1761
执笔经年
执笔经年 2021-02-05 03:07

I originally thought Python was a pure pass-by-reference language.

Coming from C/C++ I can\'t help but think about memory management, and it\'s hard to put it out of my

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 03:33

    Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

    As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

    my_list = [1,2,3]
    for member in my_list:
        member = 42
    print my_list
    

    Output:

    [1, 2, 3]

    If you want to change a list containing immutable types, you need to do something like:

    my_list = [1,2,3]
    for ndx, member in enumerate(my_list):
        my_list[ndx] += 42
    print my_list
    

    Output:

    [43, 44, 45]

    If your list contains mutable objects, you can modify the current member object directly:

    class C:
        def __init__(self, n):
            self.num = n
        def __repr__(self):
            return str(self.num)
    
    my_list = [C(i) for i in xrange(3)]
    for member in my_list:
        member.num += 42
    print my_list
    

    [42, 43, 44]

    Note that you are still not changing the list, simply modifying the objects in the list.

    You might benefit from reading Naming and Binding.

提交回复
热议问题