Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am new to programming and I am having trouble with the below 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)

1 Answer

0 votes
by (36.8k points)

This is the 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 want recursion, you can simply do the following code:

def list_to_string2(values):

    return ", ".join(map(str, a))

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...