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=", ")
[1, 2, 3, 4, 5] 1, 2, 3, 4, 5
2. Print List using
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))
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)))
1 2 3 4 5
3. Printing List Items with
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])
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
from index is inclusive and
to index is exclusive.
# List digitsList = [0, 1, 2, 3, 4, 5] # Print Sublist print(digitsList[1:3])
Happy Learning !!