How to print numbers on a new line in Python

avatar

Borislav Hadzhiev

Last updated: Sep 5, 2022

banner

Photo from Unsplash

Print numbers on a new line in Python #

To print numbers on a new line:

  1. Use a for loop to iterate over the sequence.
  2. Use the print() function to print each number on a separate line.
main.py
# ✅ print string containing numbers on separate lines numbers = '2,4,8' for number in numbers.split(','): # 2 # 4 # 8 print(int(number)) # -------------------------------------------- # ✅ print list of numbers on separate lines numbers = [2, 4, 8] result = '\n'.join(str(number) for number in numbers) # 2 # 4 # 8 print(result) # -------------------------------------------- # ✅ print range of numbers on separate lines for i in range(1, 4): # 1 # 2 # 3 print(i)

The first example splits a string containing numbers and prints them on separate lines.

main.py
numbers = '2,4,8' for number in numbers.split(','): # 2 # 4 # 8 print(int(number))

You can also use a for loop if you need to print a list of numbers on separate lines.

main.py
numbers = [2, 4, 8] for number in numbers: # 2 # 4 # 8 print(number)

Alternatively, you can join the list of numbers with a newline (n) character separator.

main.py
numbers = [2, 4, 8] result = '\n'.join(str(number) for number in numbers) # 2 # 4 # 8 print(result)

We used a generator expression to iterate over the list of numbers.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the str() class to convert the current number to a string.

The last step is to join the strings with a newline (\n) separator.

If you need to print the numbers in a range on separate lines, use the range() class.

main.py
for i in range(1, 4): # 1 # 2 # 3 print(i)

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

main.py
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)
The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1.

If values for the start and stop parameters are provided, the start value is inclusive, whereas the stop value is exclusive.

main.py
result = list(range(1, 5)) # 👇️ [1, 2, 3, 4] print(result)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.