Kodeclik Blog

Print a Python List (5 ways)

Let us assume I have a list comprising the 12 months as follows:
Assume our goal is to print this list. How do we do it? Learn about 5 different ways!

Method 1: Use a vanilla print

You can simply do
which will produce the output
Now, notice that by default printing a list will yield the square brackets. If you do not desire the square brackets you should explore one of the methods below.

Method 2: Use a for loop

We can create a for loop to run through the indices of the list. We can setup the extent of the for loop using the range operator applied on the list length, as follows:
This will produce the output:

Method 3: Use an iterator

Of course, because Python has first class iterators you can write much cleaner code as follows:
Note that in the above code, x refers to the actual elements of the list, like ‘Jan’, ‘Feb’, and so on. In the previous program, x referred to indices such as 0, 1, and so on.
The output is still the same:

Method 4: Use a join function

The join function takes the elements of a list and concatenates them using a specified separator.
If we do:
We are using the comma symbol as a separator. So this line will print:
To obtain the same output as before, you can do:
This will yield:
Of course, you can do both:
This will produce:

Method 5: Use the * symbol

Prefixing the list with an asterisk and printing it is another way. Let us see what that does and how it differs from vanilla printing (our Method 1 presented earlier). Consider the following code:
The output is:
Note that in the vanilla printing approach, you get the square brackets and commas separating the values. Using the * symbol we do not have these decorations.
You can also give separators, like so:
The output is:
There you have it - 5 different ways to print a Python list! Which one is your favorite?
If you liked learning about printing lists, checkout our blog post on Python print() and also four different ways toprepend items to a list.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2022. All rights reserved.