Saud Tanvir
Saud Tanvir

Reputation: 19

Understanding how functions with lists work

def trick(l,i):
    if i==1:
        return l[0]
    else:
         return l[1]
def foo(x):
    x[0]='def'
    x[1]='abc'
    return x[1]
q=['abc','def']
print (trick(q,1)==foo(q))
print (trick(q,1)==foo(q))
print (trick(q,0)== foo(q))

When I run this it prints True, False, True. But since foo() always returns the same thing shouldn't it be True,True, False. Is one of these functions changing the input list q somehow? Because the return from any of these functions should be independent of the original list.

Upvotes: 0

Views: 88

Answers (1)

Michael Recachinas
Michael Recachinas

Reputation: 2749

Given that lists in Python are mutable, if you pass a list into a method, behind the scenes, you're actually passing the reference to that list, which means if you mutate the list in the method, you are mutating the list for everyone who references that list.

Consider the simple example:

def foo(lst):
    lst[0] = 3

test_list = ["hello", "world"]
print test_list # prints ['hello', 'world']
foo(test_list) # mutates `test_list` by setting `test_list[0] = 3`
print test_list # prints [3, 'world']

In your case,

def trick(l,i):
    if i==1:
        return l[0]
    else:
         return l[1]
def foo(x):
    x[0]='def'
    x[1]='abc'
    return x[1]
q=['abc','def']

# in the below line, Python first evaluates `trick(q, 1)`
# which returns 'abc'. Then Python evaluates `foo(q)`, which
# mutates `q` to `['def', 'abc']` and returns the new `q[1]`,
# or 'abc'. Therefore, this statement evaluates to `True`.
print (trick(q,1)==foo(q))

# in the below line, Python evaluates `trick(q, 1)` with the
# newly mutated `q` and so returns 'def'. `foo(q)` again modifies
# `q` to `['def', 'abc']` and returns 'abc'. Therefore, the statement
# evaluates to `False`.
print (trick(q,1)==foo(q))

# this last statement evaluates to True because `trick(q, 0)` returns
# 'def', which is the same as what `foo(q)` returns.
print (trick(q,0)== foo(q))

Upvotes: 4

Related Questions