0

I want to convert a list to a string and using the following lines of code to find my desired string.

My Code

def list_to_string2(values):
    num = ""
    x=0
    x= values[x]
    num += str(x)
    if len(values) == 0:
        return num
    else:
        return list_to_string2(values) + values.pop(0)

values = [1, 2, 3, 4, 5]
s2 = list_to_string2(values)
print(s2)

Getting an issue like this: RecursionError: maximum recursion depth exceeded while getting the str of an object

I am having trouble with this challenge as I'm in the beginner stage of programming.

Your assistance is highly appreciated. Thank you.

KittoMi
  • 411
  • 5
  • 19
  • @Rakesh Those are not good duplicates. The question here is to fix a recursive function, not a generic way to join a list. – Selcuk Oct 15 '20 at 05:46
  • Does this answer your question? [How to convert list to string](https://stackoverflow.com/questions/5618878/how-to-convert-list-to-string) – KittoMi Oct 15 '20 at 06:07

1 Answers1

0

This is a fixed version of your code:

def list_to_string2(values, num=""):
    s = str(values[0])
    if len(values) == 1:
        return num + s
    else:
        num += s + ", "
        return list_to_string2(values[1:], num)

If you don't need recursion, you can simply do the following:

def list_to_string2(values):
    return ", ".join(map(str, a))

map(str, ...) will convert each item to a string, and ", ".join() will join those elements using ", " as a separator.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Thank you so much! If you don't mind me asking can you explain to me your thought process for solving this problem – Pelican Man Oct 15 '20 at 05:46
  • Sure, but you were close enough. You should basically pass your progress so far back to the recursive function to be able to keep state. You were simply creating the `num` from scratch in every loop. – Selcuk Oct 15 '20 at 05:48