1

I'm new in Python. I can't understand the result of the following code. Why do the second call return value contain the first one?

def first(l_list):
    return l_list[:1][0]

def rest(l_list):
    return l_list[1:]

def map(f, src_list, dst_list=[]):
    if src_list:
        dst_list.append(f(first(src_list)))
        map(f, rest(src_list), dst_list)
    return dst_list

def inc(num):
    return num + 1

def pow(num):
    return num**2

mylist = list(range(10))

print(map(inc, mylist))
print(map(pow, mylist))

The results are

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

I expected the following results

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Thanks for any help!

Update

I modified the 'map' function and it is working now as I expected.

def map(f, src_list, dst_list=None):
    if dst_list is None:
        dst_list = []
    if src_list:
        dst_list.append(f(first(src_list)))
        map(f, rest(src_list), dst_list)
    return dst_list
tkircsi
  • 315
  • 3
  • 14
  • 1
    This is because (a) lists are mutable, and you're mutating your shared `mylist`, and (b) default argument values are created at function definition time, not at each call, so you're also mutating your shared `dst_list` default. – abarnert Jul 03 '18 at 20:48
  • If you can explain which part of that your'e confused by, there are duplicate questions with answers that nicely explain both, which we can link for you. Also see [the official FAQ](https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects). – abarnert Jul 03 '18 at 20:48
  • Thanks @abarnert ! This was the missing part for me "..default argument values are created at function definition time, not at each call..." – tkircsi Jul 03 '18 at 20:52
  • Well, thank Prune for guessing that was the one you wanted and finding the dup for that one before I managed to ask, but glad you got your answer quickly. – abarnert Jul 03 '18 at 21:07

0 Answers0