How to concatenate all items in a list in Python

Python provides a range of modules and functions. Lists are structures used to store multiple items. They are one of four structures used to hold data in Python, the others being tuples, sets, and dictionaries. Lists can store items of any data type, allowing items of different data types to be in the same list. They can hold data in any order, and duplicates are stored separately. To concatenate a list of strings, use the join() method with a separator string.

Syntax

string.join(iterable)

Parameters

  1. string: The specified separator; this is required. The separator is added between the items that are being concatenated.
  2. iterable: An iterable that only has items of data type string. Any other data type will result in an error. This parameter is required.

Return value

The join method returns a string that contains all items of the iterable, separated by the specified string.

For example, if we want to concatenate the items of the list [‘i’, ‘love’, ‘cats’] with the separator ‘-’, our output will be i-love-cats.

Code example

In the code below, we concatenate the items of three lists with different separators.

#initialize the lists
list1=["cat", "dog", "mouse", "bird"]
list2=["i", "am", "16", "years", "old"]
list3=["1", "2", "3", "4", "5", "6"]
#concatenate the lists
string1=' '.join(list1)
string2='-'.join(list2)
string3='#'.join(list3)
#print the concatenated strings
print(string1)
print(string2)
print(string3)

Free Resources