Skip to content Skip to sidebar Skip to footer

Recursively Copy A List To Another In Python

I want to copy a list to another recursively in python. For that purpose, i have taken string as input, defined an empty list and send them to recursive function as lists, so that

Solution 1:

return string_copy(k,s.append(k[i]),i+1)

The list append() method does not return the updated list; it adds the new item in-place and returns None.

Therefore the next call to string_copy() will have None as the value for s.

Solution 2:

The final solution is:

defstring_copy(k,s,i):
  if (i == len(k)):
    return s
  else:
    s.append(k[i])
    return string_copy(k,s,i+1)

defmain():
   print("enter the string you want to copy:")
   k = input()
   s = ""
   i = 0;
   print("the type of k is:", type(k))
   res = string_copy(list(k),list(s),i)
   print("the desired results are:","\n", "".join(res))
if __name__ == "__main__": main()        

Better way of approaching this problem:

defstring_copy(k):
  if (len(k) == 0):
    return k
  else:
    return k[0] + string_copy(k[1:])

defmain():
  print("enter the string you want to copy:")
  k = input()
  print("the type of k is:", type(k))
  res = string_copy(k)
  print("the copied string is:","\n",res)
if __name__ == "__main__": main()  

Post a Comment for "Recursively Copy A List To Another In Python"