Alexey
Alexey

Reputation: 1438

default value for the function python

I'm trying to understand this question and answers:

python function default parameter is evaluated only once?

in order to understand it i try:

def f1(a, L=[]):
    if not L:
        print "L is empty"
        L = []
    L.append(a)
    return L

>>>f1(1)
L is empty
[1]
>>>f1(1)
L is empty
[1]

def f2(a, L=[]):
        if L:
            print "L isn't empty"
            L = []
        L.append(a)
        return L

>>>f2(1)
[1]
>>>f2(1)
L isn't empty
[1]

So I think in the case of f1 L is becoming empty again every time - it is assigned to [] again after every call of f1. But in case of f2 L is somehow isn't empty? Why?

Upvotes: -1

Views: 149

Answers (1)

badp
badp

Reputation: 11813

When you do this:

L = []

...you don't change the value referenced by L; you change the reference L to point to a brand new list [].

If you want to empty the list referenced by L without changing the reference itself, you can write:

del L[:]

...or use methods such as remove or pop that work by changing the current list.


Here's f1 and f2 in animated form to help you understand. (Click for webm. Wait for each gif to fade to white. The gifs don't sync up, sorry.)

f1

f2

Upvotes: 6

Related Questions