0
0
PythonHow-ToBeginner · 3 min read

How to Join List of Strings in Python: Simple Guide

In Python, you can join a list of strings into a single string using the join() method of a string separator. For example, ' '.join(['Hello', 'world']) combines the list into 'Hello world'.
📐

Syntax

The basic syntax to join a list of strings is:

  • separator.join(list_of_strings)

Here, separator is the string placed between each element, and list_of_strings is the list you want to join.

python
separator.join(list_of_strings)
💻

Example

This example shows how to join a list of words with spaces and commas.

python
words = ['apple', 'banana', 'cherry']
joined_with_space = ' '.join(words)
joined_with_comma = ', '.join(words)
print(joined_with_space)
print(joined_with_comma)
Output
apple banana cherry apple, banana, cherry
⚠️

Common Pitfalls

One common mistake is trying to join a list that contains non-string items, which causes an error. Always ensure all items are strings before joining.

Another mistake is using join() as a list method, which is incorrect because join() belongs to strings.

python
# Wrong: calling join on list
# words = ['apple', 'banana', 'cherry']
# result = words.join(', ')  # This raises AttributeError

# Right: calling join on string separator
words = ['apple', 'banana', 'cherry']
result = ', '.join(words)
print(result)

# Wrong: list with non-string items
# items = ['apple', 2, 'cherry']
# ', '.join(items)  # Raises TypeError

# Right: convert all to strings first
items = ['apple', 2, 'cherry']
result = ', '.join(str(item) for item in items)
print(result)
Output
apple, banana, cherry apple, 2, cherry
📊

Quick Reference

Remember these tips when joining strings:

  • Use a string as the separator (like space, comma, or empty string).
  • Call join() on the separator string, not on the list.
  • Make sure all list elements are strings before joining.

Key Takeaways

Use separator.join(list_of_strings) to join strings with a separator.
The separator is a string placed between list elements in the result.
All items in the list must be strings before joining.
Calling join() on the list itself causes an error.
Convert non-string items to strings before joining if needed.