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