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.
string.join(iterable)
string
: The specified separator; this is required. The separator is added between the items that are being concatenated.iterable
: An iterable that only has items of data type string. Any other data type will result in an error. This parameter is required.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
.
In the code below, we concatenate the items of three lists with different separators.
#initialize the listslist1=["cat", "dog", "mouse", "bird"]list2=["i", "am", "16", "years", "old"]list3=["1", "2", "3", "4", "5", "6"]#concatenate the listsstring1=' '.join(list1)string2='-'.join(list2)string3='#'.join(list3)#print the concatenated stringsprint(string1)print(string2)print(string3)