Thursday, December 26, 2024
Google search engine
HomeLanguagesPython program to Concatenate all Elements of a List into a String

Python program to Concatenate all Elements of a List into a String

Given a list, the task is to write a Python program to concatenate all elements in a list into a string i.e. we are given a list of strings and we expect a result as the entire list is concatenated into a single sentence and printed as the output.

Examples:

Input:  ['hello', 'geek', 'have', 'a', 'geeky', 'day']
Output: hello geek have a geeky day

Using the Naive approach to concatenate items in a list to a single string 

Here, we are taking a list of words, and by using the Python loop we are iterating over each element and concatenating words with the help of the “+” operator.

Python3




l = [ 'hello', 'geek', 'have',
     'a', 'geeky', 'day']
 
ans = ' '
for i in l:
   
  # concatenating the strings
  # using + operator
  ans = ans+ ' '+ i
   
print(ans)


Output:

hello geek have a geeky day

Using list comprehension to concatenate items in a list to a single string 

Here, we are using list comprehension to make the items into a Python string i.e. words into sentence. 

Python3




l = [ 'hello', 'geek', 'have',
     'a', 'geeky', 'day']
 
res = " ".join([str(item) for item in l])
res


Output:

'hello geek have a geeky day'

Using join() method to concatenate items in a list to a single string 

The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string. 

Python3




# code
l = ['hello', 'geek', 'have',
   'a', '1', 'day']
 
# this will join all the
# elements of the list with ' '
l = ' '.join(l)
print(l)


Output:

hello geek have a 1 day

Using map() method to concatenate items in a list to a single string

The map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable. In map we passed the str as Datatype and list, this will iterate till the length of the list and join each element to form a string.

Python3




l = [ 'hello', 'geek', 'have',
     'a', 'geeky', 'day']
 
res = " ".join(map(str, l))
print(res)


Output:

hello geek have a geeky day

Using reduce() method to concatenate items in a list to a single string 

The reduce(fun, seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in “functools” module.

Python3




from functools import reduce
 
l = ['hello', 'geek', 'have',
     'a', 'geeky', 'day']
 
# Concatenate all items in list to a string
res = reduce(lambda x, y: x + ' ' + y, map(str, l))
print(res)


Output:

hello geek have a geeky day

The time and space complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

RELATED ARTICLES

Most Popular

Recent Comments