Python Print List

Learn to print a List in Python using different ways.

1. Printing List Items in Single Line seperated by Comma

Python program to print the items of a List in a single line, and the printed list items are separated by a comma in between. The Last character of the List is not a comma, its a new line so that next print statement prints into the new line.

To print only the List items without the square brackets, use the * asterisk operator which unpack the List items.

# List
digitsList = [1, 2, 3, 4, 5] 

# Print the List 
print(digitsList, sep=", ", end="\n")

# Print the List Items
print(*digitsList, sep=", ")

Program output.

[1, 2, 3, 4, 5]
1, 2, 3, 4, 5

2. Print List using join() and map() Methods

The join() method returns a string in which the items of the List have been joined by a given separator.

# List
strList = ["a", "b", "c", "d", "e"] 
  
# Join list items
print(' '.join(strList))  

Program output.

a b c d e

We can use map() to convert each item in the List to a string it is not a String, and then join all the items.

# List
digitsList = [1, 2, 3, 4, 5] 
  
# Join list items
print(' '.join(map(str, digitsList))) 

Program output.

1 2 3 4 5

3. Printing List Items with for Loop

Python program to print all the items in the List using a for loop. We are using the end argument to print the List items in the same line.

Use the len() method to check the length of List so the Loop can make that number of iterations.

# List
digitsList = [1, 2, 3, 4, 5] 
  
# Printing the list using loop 
for i in range(len(digitsList)): 
    print(digitsList[i])

Program output.

1
2
3
4
5

4. Printing A Sublist

Python example which uses the array slicing method to print a subset of items from a List. Note that indices start from 0.

The from index is inclusive and to index is exclusive.

# List
digitsList = [0, 1, 2, 3, 4, 5] 
  
# Print Sublist
print(digitsList[1:3])

Program output.

[1, 2]

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.