Skip to content

Python print list – Using Loops, Maps | 4 Ways

  • by

Python List is the most frequently used and very versatile datatypes in Python. It’s easy to make a list but how you will do program a python code to print list elements?

Python print list Using Loops, Maps different Ways

In this tutorial, we will do a python program only for a print full list. Here are way some ways to print a list in python:-

Let’s start Print lists in Python

For loop Statment:-

The easy way to do it with for loop, it’s print all elements of the python list one by one.


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

# printing the list using for loop
for x in range(len(num)):
    print (num[x])

Output: 1
2
3
4
5

While loop Statment:-

Same easy as for loop, In the below code we have a num list with 5 elements. Then one count variable to check condition. Then while loop has a condition run until true expression.


num = [1, 2, 3, 4, 5]
count = 0;

# printing the list using while loop
while (count < len(num)):
    print (num[count])
    count= count+1

Output: 1
2
3
4
5

Convert a list to a string

As an upper example with loops, we see an example for a list with a number. But you can use the same method with the string list.

There is also an option for a string list to print. Using join() function but for string, you have to convert it to string list then use join() function.

# string list
str_list = ["Python", "String", "example"]

# print the list using join function() 
print(' '.join(str_list))


# number list
num = [1, 2, 3, 4, 5]
# convert and print the list using join function()
print (str(num)[1:-1])

Output: Python String example
1, 2, 3, 4, 5

map() function

Use the map() function to convert each element of the list into a string if the list is not a string and then use the join function to join them.

num = [1, 2, 3, 4, 5] 
print(' '.join(map(str, num))) 

Output: 1 2 3 4 5

Question: Print a list of space-separated elements in Python 3?

Answer: To get this you have to apply the list as separate arguments: print(*List)

See below example

num = [1, 2, 3, 4, 5]
print(*num)
print(*num, sep =', ')
print(*num, sep =' -> ')

Output: 1 2 3 4 5
1, 2, 3, 4, 5
1 -> 2 -> 3 -> 4 -> 5

This is the easiest method Unless you need the joined string for something else. Otherwise, use str.join():

Do comment if you have a any doubt and suggestion on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading