Python map function, passing by reference/value?

前端 未结 3 1957
天命终不由人
天命终不由人 2021-01-12 11:23

I have a question about the map function in Python.

From what I understand, the function does not mutate the list it\'s operating on, but rather create

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 12:00

    I want to bump this. The answers don't really answer the question - they disregard the fact that the OP was able to achieve the desired result by iterating. The question comes down to the behavior of map. Here is a more direct example:

    f=(lambda pair: pair[0].append(pair[1]))
    a = ([],1)
    f(a)
    print(a) #prints ([1],1)
    a=([],1)
    map(f,[a])
    print(a) #prints ([0],1)
    

    So map isn't mutating objects in the way the OP is expecting. I have the same confusion.

    Can anyone comment on exactly what is going on here? I think that'd be a good answer to the OP's question.

    Note that we have different behavior if we assign the output of map as follows (as per Cat Plus Plus' answer)

    f=(lambda pair: pair[0].append(pair[1]))
    a = ([],1)
    x = [a]
    x[:] = map(f,x)
    print(x) #prints None
    print(a) # prints [1]
    

    Please note that in the first example, we simply called f(a), not a=f(a). Why do we need assignment when using map and not when working outside of map?

提交回复
热议问题