I want to append to a list recursively but I cannot come up with a function that works. The function takes two arguments times
and data
. times
should be the number of times to append the data.
Here is my code so far:
def replicate_recur(times, data):
result2 = []
if times == 0:
result2.append(data)
else:
result2.append(data)
replicate_recur(times - 1, data)
return result2
You could use a intermediate list to append to in each recursive call. That avoids these redefinition problems you're encountering currently:
def replicate_recur(times, data, result=None):
if result is None: # create a new result if no intermediate was given
result = []
if times == 1:
result.append(data)
else:
result.append(data)
replicate_recur(times - 1, data, result) # also pass in the "result"
return result
When called:
>>> replicate_recur(4, 2)
[2, 2, 2, 2]
You can use xrange
for this, there is no point to use recursion unless it is a coding test.
def replicate(times, data):
result2 = []
for i in xrange(times):
result2.append(data)
return result2
Same function can be written in a recursive way like this:
def replicate_recur(times, data, listTest=None):
# If a list has not been passed as argument create an empty one
if(listTest == None):
listTest = []
# Return the list if we need to replicate 0 more times
if times == 0:
return listTest
# If we reach here at least we have to replicate once
listTest.append(data)
# Recursive call to replicate more times, if needed and return the result
replicate_recur(times-1, data, listTest)
return listTest
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With