Home »
Python »
Python Articles
Python - Convert list to string using recursion
By IncludeHelp Last updated : February 17, 2024
In programming, recursion is a technique that calls itself directly or indirectly and such function is known as recursive or recursion function.
Problem statement
Given a Python list, write a Python program to convert the given list to a string using Recursion.
Converting a list to string using recursion
To list to string using recursion, write a recursion function that extracts each element of the list, converts it into a string, and concatenates it to a resultant string variable.
Python program to convert list to string using recursion
The below program converts a given list to a string using the recursion function in Python:
# Recursion function to convert
# list to string
def list_to_start(start, lst, result):
if start == len(lst):
# base condition to return string
return result
# Extarct & concatenate element in
# list to result variable
result += str(lst[start]) + " "
# calling recursive function
return list_to_start(start + 1, lst, result)
# The main code
# Declaring a list
cities = ["New Delhi", "Indore", "Mumbai", "Banglore"]
# Calling function
res = list_to_start(0, cities, "")
# Printing values and their types
print("cities:", cities)
print("Type of cities:", type(cities))
print("After converting list to string")
print("res:", res)
print("Type of res:", type(res))
Output
The output of the above program is:
cities: ['New Delhi', 'Indore', 'Mumbai', 'Banglore']
Type of cities: <class 'list'>
After converting list to string
res: New Delhi Indore Mumbai Banglore
Type of res: <class 'str'>
To understand the above program, you should have the basic knowledge of the following Python topics: