Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass list to function by value

I want to pass a list into function by value. By default, lists and other complex objects passed to function by reference. Here is some desision:

def add_at_rank(ad, rank):
    result_ = copy.copy(ad)
    .. do something with result_
    return result_

Can this be written shorter? In other words, I wanna not to change ad.

like image 727
dondublon Avatar asked Mar 13 '13 04:03

dondublon


People also ask

Can you pass a list into a function?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

Is list pass by value or reference?

It's passed by value of reference. So modifications to the object can be seen outside the function, but assigning the variable to a new object does not change anything outside the function. It's essentially the same as passing a pointer in C, or a reference type in Java.

Are Python lists passed by value?

The two most widely known and easy to understand approaches to parameter passing amongst programming languages are pass-by-reference and pass-by-value. Unfortunately, Python is “pass-by-object-reference”, of which it is often said: “Object references are passed by value.”

How do you pass a copy of a list to a function in Python?

You can use [:] , but for list containing lists(or other mutable objects) you should go for copy. deepcopy() : lis[:] is equivalent to list(lis) or copy. copy(lis) , and returns a shallow copy of the list.


1 Answers

You can use [:], but for list containing lists(or other mutable objects) you should go for copy.deepcopy():

lis[:] is equivalent to list(lis) or copy.copy(lis), and returns a shallow copy of the list.

In [33]: def func(lis):
    print id(lis)
   ....:     

In [34]: lis = [1,2,3]

In [35]: id(lis)
Out[35]: 158354604

In [36]: func(lis[:])
158065836

When to use deepcopy():

In [41]: lis = [range(3), list('abc')]

In [42]: id(lis)
Out[42]: 158066124

In [44]: lis1=lis[:]

In [45]: id(lis1)
Out[45]: 158499244  # different than lis, but the inner lists are still same

In [46]: [id(x) for x in lis1] = =[id(y) for y in lis]
Out[46]: True

In [47]: lis2 = copy.deepcopy(lis)  

In [48]: [id(x) for x in lis2] == [id(y) for y in lis]  
Out[48]: False
like image 103
Ashwini Chaudhary Avatar answered Nov 14 '22 11:11

Ashwini Chaudhary