join(): join items of an iterable into one string in Python

Use the join() method to join all the items if an iterable into a string.

The basic syntax is: string.join(iterable)

As per the syntax above, a string is required as a separator.

The method returns a new string, which means that the original iterator remains unchanged.

Since the join() method only accepts strings, if any element in the iterable is of a different type, an error will be thrown.

Let’s see some examples with: string, list, tuple, set, and dictionary

join(): Strings

The join() method puts the $ sign as a separator for every character in the string.

my_string = 'beach'

print('$'.join(my_string))
#output: b$e$a$c$h

join(): Lists

I have a simple list of three items representing car brands.

The join() method is gonna use the $ sign as a separator.

It concatenates all the items on the list and puts the $ sign between them.

my_list = ['bmw', 'ferrari', 'mclaren']

print('$'.join(my_list))
#output: bmw$ferrari$mclaren

This another example remembers you that join() does not work with non-string items.

When trying to concatenate the int items, an error is raised.

my_list = [1, 2, 3]

print('$'.join(my_list))
#output:
#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#TypeError: sequence item 0: expected str instance, int found

join(): Tuples

The tuple follows the same rationale as the list example explained before.

Again, I’m using the $ sign as separator.

my_tuple = ('bmw', 'ferrari', 'mclaren')

print('$'.join(my_tuple))
#output: bmw$ferrari$mclaren

join(): Sets

Since the set is also the same as the tuple and the list, I’ve used a different separator in this example.

my_set = {'bmw', 'ferrari', 'mclaren'}
print('|'.join(my_set))
#output: ferrari|bmw|mclaren

join(): dictionaries

The dictionary has a catch when you use the join() method: it joins the keys, not the values.

This example shows the concatenation of the keys.

my_dict = {'bmw': 'BMW I8', 'ferrari': 'Ferrari F8', 'mclaren': 'McLaren 720S'}

print(','.join(my_dict))
#output: bmw,ferrari,mclaren