Python - Join List with Space character


Python - Join List with Space

To join a given list of elements with single space as separator into a Python string, call string join() method on space character " ", and pass the given list as argument to the join() method. The join() method returns a new string created by joining the elements in the list with the single space character in between them.

Now, we shall go through some examples of joining elements in a list with space character as separator between them.

1. Joining list of strings with space using string join() method

Consider that we are given a list of string elements, and we have to join them into a string with single space as separator between the elements.

Steps

  1. Given a list of strings in my_list.
  2. Call string join() method on single space character (taken as string literal), and pass the list as argument.
' '.join(my_list)
  1. The join() method returns a string created by joining the elements in the list with the space character in between them. Assign the returned value to a variable, say joined_str.
  2. You may print the returned string to the standard output using print() statement.

Program

The complete program to join the strings in a list with space character as separator.

Python Program

# Given a list
my_list = ['apple', 'banana', 'cherry']

# Join list of strings with space
joined_str = ' '.join(my_list)

print(joined_str)

Output

apple banana cherry

2. Joining list of numbers with space using string join() method

In this example, we shall take a list of numbers, and join the numbers in the list with single space character as separator between the elements.

join() method works only on the string elements. Therefore, to join the numbers in a list, you have to convert them to strings. In the following program, we have used list comprehension to convert the list of numbers into lists of strings.

Python Program

# Given a list
my_list = [10, 20, 30, 40, 50]

# Join list of numbers with space
joined_str = ' '.join([ str(x) for x in my_list])

print(joined_str)

Output

10 20 30 40 50

Summary

In this tutorial, we have seen how to join a list of elements with comma separator using string join() method, with examples.