jm_111
jm_111

Reputation: 13

Why doesn't the function change it's argument?

def func(l):
    l = l + l
    return ()
lst = [22, 33, 13]
func(lst)
print(lst)

The output is [22, 33, 13]. Why is it not [22, 33, 13, 22, 33, 13]?

Upvotes: 0

Views: 44

Answers (4)

Bill the Lizard
Bill the Lizard

Reputation: 405725

Inside the function you made the reference l point to a new list object l + l. The outside reference lst still points to the original list object.

If the function had instead modified the list object itself, by appending to it for example, you would see the effect after the function ended.

def func(l):
    l.append(42)
    print(l)
    return () # Not really needed.

lst = [22, 33, 13]
func(lst)
print(lst)

If you want to get the desired result, try using the list extend method.

def func(l):
    l.extend(l)

lst = [22, 33, 13]
func(lst)
print(lst) # prints [22, 33, 13, 22, 33, 13]

Upvotes: 1

jfaccioni
jfaccioni

Reputation: 7509

Inside the function, in the line l = l + l, you're creating a new list l based on the list passed in as an argument and losing the reference to the old list passed in as an argument in a single line.

You never modify the list outside the function (e.g. what could be done by using the append or extend method), and you never return the new list inside the function, so you don't see any changes after the function is done executing.

Upvotes: 0

BernardL
BernardL

Reputation: 5434

For starters your function returns a tuple, an empty one. It does not do anything to the list you passed it.

In any case even if you fix your function to actually return the list, you would still have to assign in to something, like below:

def func(l):
    l = l + l
    return l

lst = [22, 33, 13]
new_lst  = func(lst)

print(lst)
print(new_lst)

>>[22, 33, 13]
>>[22, 33, 13, 22, 33, 13]

Upvotes: 0

Bharat Gera
Bharat Gera

Reputation: 820

Try this:

def func(l):
    l = l + l
    return l  # return l from function space.
lst = [22, 33, 13]
lst = func(lst) # need to update lst
print(lst)

Upvotes: 0

Related Questions