I wrote a function in python that receive a list of elements, and a string as input, then return a combined list of these two paramteres recursevly. for example:
add_chars([1, 2, 3, 4, 5], "hel")
will return [1, 'h', 2, 'e', 3, 'l', 4, 5]
Here is my code:
def add_chars(some_list, some_str, result=[]):
if some_list==[]: return result
result.append(some_list[0])
if some_str!='':
result.append(some_str[0])
return add_chars(some_list[1:], some_str[1:])
print(add_chars([2, 3, 18, "what", 9, "else", 8, 5], "absolute"))
# [2, 'a', 3, 'b', 18, 's', 'what', 'o', 9, 'l', 'else', 'u', 8, 't', 5, 'e']
print(add_chars([1, 2, 3, 4, 5], "hel"))
# ([2, 'a', 3, 'b', 18, 's', 'what', 'o', 9, 'l', 'else', 'u', 8, 't', 5, 'e', 1, 'h', 2, 'e', 3, 'l', 4, 5])
I'm just working with recursion and local variables (not globals), So My problem is when I call the function second time, my result list isn't empty (because I passed result list as a parameter), and new data are adding to the old list.
How I can have a clear list when I call the function multiple times? using parameters and local variables.