What is a function parameter =[] for?

Ian Kelly ian.g.kelly at gmail.com
Wed Nov 18 17:47:00 EST 2015


On Wed, Nov 18, 2015 at 3:38 PM, fl <rxjwg98 at gmail.com> wrote:
> On Wednesday, November 18, 2015 at 5:12:44 PM UTC-5, Ian wrote:
>> On Wed, Nov 18, 2015 at 2:08 PM, fl <com> wrote:
>> > Hi,
>> >
>> > I have tried the below function and find that it can remember the previous
>> > setting value to 'val'. I think the second parameter has something on this
>> > effect, but I don't know the name and function of '=[]' in this application.
>> >
>> > Could you explain a little to me?
>> > Thanks,
>> >
>> >
>> > def eList(val, list0=[]):
>> >     list0.append(val)
>> >     return list0
>> > list1 = eList(12)
>> > list1 = eList('a')
>>
>> The list0 parameter has a default value, which is [], an initially
>> empty list. The default value is evaluated when the function is
>> defined, not when it is called, so the same list object is used each
>> time and changes to the list are consequently retained between calls.
>
> Thanks. The amazing thing to me is that the following two line codes:
> list1 = eList(12)
> list2 = eList('a')
>
> will have both list1 and list2 the same cascaded values:
>
> list1
> Out[2]: [12, 'a']
>
> list2
> Out[3]: [12, 'a']
>
> I have known object concept in Python.
> 1. Why do they have the same list value?
>  Function eList must be for this purpose?

Because eList returns list0, and as explained above list0 is the same
list in both calls. Therefore list1 and list2 are the same list.

> 2. If I want to have two separate lists, how to avoid the above result?
>  Function eList is not for this purpose?

The usual advice is to not use a mutable object as the default value.
If you want the default to be an empty list, it's usually better set
it to None and then make it an empty list if the value is None. For
example:

def eList(val, list0=None):
    if list0 is None:
        list0 = []
    list0.append(val)
    return list0



More information about the Python-list mailing list