3.4. List Joins#
When we print lists they’ll be displayed using square brackets with list items separated by commas.
todo = ["Buy carrots", "Wash car", "Study for quiz"]
print(todo)
Sometimes we want to display list items differently. To help us, we can use the
.join()
method. This allows us to join all the elements in a list together
with a specified separator.
Here is the syntax for joining:
separator.join(list)
Here is an example where we use the separator ', '
( a comma followed by a
space).
todo = ['Buy carrots', 'Wash car', 'Study for quiz']
print(', '.join(todo))
Buy carrots, Wash car, Study for quiz
You’ll notice that the separate only goes between list items and doesn’t appear at the start or at the end.

Here is another example where use use '\n'
(a newline character).
todo = ['Buy carrots', 'Wash car', 'Study for quiz']
print('\n'.join(todo))
Buy carrots
Wash car
Study for quiz
Note that .join()
can only be used on lists containing strings. The
following will result in an error since the list elements are integers.
numbers = [7, 4, -1, 3]
print(", ".join(numbers))
Traceback (most recent call last):
File "/home/main.py", line 2, in <module>
print(', '.join(numbers))
^^^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, int found
Question 1
What do you think the output of the following code will be?
letters = ['a', 'b', 'c', 'd', 'e']
print('-'.join(letters))
-a-b-c-d-e-
a-b-c-d-e
-a-b-c-d-e
a-b-c-d-e-
Solution
-a-b-c-d-e-
a-b-c-d-e
-a-b-c-d-e
a-b-c-d-e-
Here we use '-'
as the separator. This will only appear between each element of the list after they are joined, i.e. it won’t appear on either end.
Question 2
What do you think the output of the following code will be?
days = ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']
print('| ' + ' | '.join(days) + ' |')
Mon|Tue|Wed|Thur|Fri|Sat|Sun
|Mon|Tue|Wed|Thur|Fri|Sat|Sun|
Mon | Tue | Wed | Thur | Fri | Sat | Sun
| Mon | Tue | Wed | Thur | Fri | Sat | Sun |
Solution
Solution is locked
Question 3
Which of the following code snippets would result in the output
5... 4... 3... 2... 1
numbers = [5, 4, 3, 2, 1] print('...'.join(numbers))
numbers = [1, 2, 3, 4, 5] print('...'.join(numbers))
numbers = ['5', '4', '3', '2', '1'] print('...'.join(numbers))
numbers = ['5', '4', '3', '2', '1'] print('... '.join(numbers))
Solution
Solution is locked
Code challenge: Charm Bracelet
You have been provided with a list of charms. Each charm is provided in Unicode that corresponds to your emoji.
charms = ['\U0001F517', '\U0001F3B1', '\U0001F9F8', '\U0001F369', '\U0001F3A0', '\U0001FA9D']
For example, you can print the 8-ball emoji using the following.
print('\U0001F3B1')
🎱
Write a program that joins each emoji with ' ------- '
(7 dashes with a space at the start and the end). This will form a charm bracelet with a link and hook at the ends of either bracelet. Print the charm bracelet. It should look like this:
🔗 ------- 🎱 ------- 🧸 ------- 🍩 ------- 🎠 ------- 🪝
Solution
Solution is locked