w3resource

Python: Concatenate all elements in a list into a string

Python Basic: Exercise-27 with Solution

Write a Python program that concatenates all elements in a list into a string and returns it.

Pictorial Presentation:

Concatenate all elements in a list into a string and return it

Sample Solution:

Python Code:

# Define a function called concatenate_list_data that takes a list as a parameter.
def concatenate_list_data(lst):
    result = ''  # Initialize an empty string called result.
    
    # Iterate through the elements in the list.
    for element in lst:
        result += str(element)  # Convert each element to a string and concatenate it to the result.

    return result  # Return the concatenated string.

# Call the concatenate_list_data function with a list of numbers and print the result.
print(concatenate_list_data([1, 5, 12, 2]))

Sample Output:

15122

Explanation:

The said code defines a function called "concatenate_list_data" that takes a list as its argument. Inside the function, it creates an empty string variable called "result".

Then it uses a for loop to iterate through each element in the input list. For each iteration, it converts the current element to a string using the str() function and concatenates it to the "result" variable.

Upon completion of the for loop, the variable "result" is returned.

The last line of code calls the "concatenate_list_data" function with a list of integers ([1, 5, 12, 2]) as an argument, it will print a string "15122".

Flowchart:

Flowchart: Concatenate all elements in a list into a string and return it.

Python Code Editor:

 

Previous: Write a Python program to create a histogram from a given list of integers.
Next: Write a Python program to print out all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-basic-exercise-27.php