Join a list with a newline character in Python

avatar

Borislav Hadzhiev

Last updated: Jun 18, 2022

banner

Check out my new book

Join a list with a newline character in Python #

To join a list with a newline character in Python:

  1. Call the join() method on a string containing a newline char ('\n').
  2. Pass the list to the join method.
  3. The result will be a string containing the list items separated by a newline.
main.py
my_list = ['one', 'two', 'three'] result = '\n'.join(my_list) # 👇️one # two # three print(result)

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your list contains numbers, or other types, convert all of the values to string before calling join().

main.py
my_list = ['one', 'two', 'three', 4, 5] result = '\n'.join(map(str, my_list)) # 👇️one # two # three # 4 # 5 print(result)

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We used the function to convert each item in the list to a string, before passing the items to the str.join() method.

The string the join() method is called on is used as the separator between elements.

main.py
my_list = ['one', 'two', 'three'] result = '-'.join(my_list) # 👇️one # two # three print(result) # 👉️ 'one-two-three'

To join the list items into a string with a newline separator, call the join method on a string that contains a newline character ('\n').

main.py
my_list = ['one', 'two', 'three'] result = '\n'.join(my_list) # 👇️one # two # three print(result)
Use the search field on my Home Page to filter through my more than 3,000 articles.