1

Say I define a function

def fun(x, dic = {}):
    dic[x] = x
    return dic

and place this function in a four loop so that I have

lst = [0, 1, 2]

for i in range(len(lst)):
    print fun(lst[i])

The four loop outputs

{0: 0}
{0: 0, 1: 1}
{0: 0, 1: 1, 2: 2}

This appears to mean that 'dic' is not resetting to the default '{}' on each iteration of the loop. Note however that if I instead run the four loop

for i in range(len(lst)):
    print fun(lst[i], dic = {})

I get the appropriate 'output'

{0: 0}
{1: 1}
{2: 2}

I was hoping that someone could explain why 'dic' is not resetting and if you knew a way around setting the default parameter in the four loop.

ayhan
  • 64,199
  • 17
  • 170
  • 189
T-Ray
  • 217
  • 2
  • 8

0 Answers0