Concatenate all Elements of a List into a String - Python
We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day".
Using str.join()
str.join() method is the most efficient way to concatenate a list of strings in Python. It combines the elements of the list into a single string using a specified separator, reducing the overhead of repeatedly creating new strings.
li = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
ans = ' '.join(li)
print(ans)
Output
hello geek have a geeky day
Explanation:
- ' '.join(li) joins the elements of the list li into a single string, with a space between each word.
- ans = ' '.join(li) stores the joined string in the variable ans .
Table of Content
Using map()
map() function applies a specified function to each element and str.join() combines them with a separator. This method is particularly useful when the list elements are not already strings and it remains efficient in terms of both time and memory.
li = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
ans = ' '.join(map(str, li))
print(ans)
Output
hello geek have a geeky day
Explanation:
- map(str, l):This converts each element of the list l to a string (though they are already strings here).
- ' '.join():This combines the elements with a space separator resulting in a single string.
Using List comprehension
This method involves creating a new list using list comprehension and then joining the elements with a separator using str.join().
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
ans = ' '.join([i for i in l])
print(ans)
Output
hello geek have a geeky day
Explanation:
- [i for i in l]: This creates a copy of the list l without transforming the elements.
- ' '.join(...): This joins the elements of the list into a single string, with a space between each element.
Using reduce()
reduce() function applies a given function cumulatively to the items of a list from left to right. In this case, it combines the strings in the list with a space separator.
from functools import reduce
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
ans = reduce(lambda x, y: x + ' ' + y, l)
print(ans)
Output
hello geek have a geeky day
Explanation: reduce(lambda x, y: x + ' ' + y, l) applies the lambda function to combine each element in the list l into a single string with spaces between them.