Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Print a Python List Beautifully [Click & Run Code]

#1
Print a Python List Beautifully [Click & Run Code]

How to print a Python list in a beautiful and fully customizable way?

This article shows you six effective ways of doing it. By studying these alternatives, you’ll not only learn how to print lists in Python, you’ll become a better coder overall.

If you just want to know the best way to print a list in Python, here’s the short answer:

  • Pass a list as an input to the print() function in Python.
  • Use the asterisk operator * in front of the list to “unpack” the list into the print function.
  • Use the sep argument to define how to separate two list elements visually.

Here’s the code:

# Create the Python List
lst = [1, 2, 3, 4, 5] # Use three underscores as separator
print(*lst, sep='___')
# 1___2___3___4___5 # Use an arrow as separator
print(*lst, sep='-->')
# 1-->2-->3-->4-->5

Try It Yourself in Our Interactive Code Shell:

This is the best and most Pythonic way to print a Python list. If you still want to learn about alternatives—and improve your Python skills in the process of doing so—keep reading!

Method: Use Default print() Statement


The default print() statement converts the list into a string representation that encloses the list elements in the square brackets [ and ], and separates two subsequent elements with the comma and an empty space a, b. This is the standard list representation.

lst = [1, 2, 3, 4, 5]
print(lst)

The output is the following:

[1, 2, 3, 4, 5]

Advantages Disadvantages
Easy to read and write Non-customizable
Fast
Concise

Try It Yourself in Our Interactive Code Shell:

The next method overcomes the main disadvantage of being not very customizable.

Method: Iterate In a For Loop


If you want full control about the output of each list element, you can use the straightforward approach of using a for loop to iterate over each element x in the list. You can then decide for yourself how to print each element.

# Create the Python List
lst = [1, 2, 3, 4, 5] # Iterate over each element x
# in the list and customize printing
for x in lst: print('Element: ' + x)

The output is the following:

Element: 1
Element: 2
Element: 3
Element: 4
Element: 5

Advantages Disadvantages
Fully customizable Relatively slow
Simple Less concise
Newline after each element

Try It Yourself in Our Interactive Python Shell:

Method: Iterate in For Loop with End Argument


If you’d rather print all elements in a single line, separated by three whitespace characters, you can do so by defining the end argument of the print() function that defines which character is added after each element that was printed to the shell (default: new-line character \n):

# Create the Python List
lst = [1, 2, 3, 4, 5] # Iterate over each element x
# in the list and customize printing
for x in lst: # Use the end argument to define # what to print after each element print(str(x), end=' ')

The output is:

1 2 3 4 5 

You see that the end argument overwrites the default behavior of printing a new-line character at the end of each element. Instead, each two elements are separated by three empty spaces.


Advantages Disadvantages
Fully customizable Relatively slow
Simple Less concise

Try It Yourself in Our Interactive Code Shell:

Let’s overcome the disadvantage of the for loop of being less concise!

Method: Unpacking With Separator Argument


The print() function works with an iterable as input. You can use the asterisk operator * in front of the list to “unpack” the list into the print function. Now, you can use the sep argument of the print() function to define how to separate two elements of the iterable.

# Create the Python List
lst = [1, 2, 3, 4, 5] # Use three underscores as separator
print(*lst, sep='___')
# 1___2___3___4___5 # Use an arrow as separator
print(*lst, sep='-->')
# 1-->2-->3-->4-->5

The sep argument allows you to define precisely what to put between each pair of elements in an iterable. This allows you full customization and keeps the code lean and concise.


Advantages Disadvantages
Fully customizable Harder to read for beginners
Fast
Concise

Try It Yourself in Our Interactive Code Shell:

This is the best and most Pythonic way to print a Python list. If you still want to learn about alternatives, keep reading.

Method: Use the string.join() Method


The string.join(iterable) method joins together all elements in the iterable, using the string as a separator between two elements. Thus, it works exactly like the sep argument of the print() function.

# Create the Python List
lst = ['1', '2', '3', '4', '5'] # Use three underscores as separator
print('___'.join(lst))
# 1___2___3___4___5 # Use arrow as separator
print('-->'.join(lst))
# 1-->2-->3-->4-->5

Note that you can only use this methods if the list elements are already strings. If they are integers, joining them together doesn’t work and Python throws an error:

TypeError: sequence item 0: expected str instance, int found

Advantages Disadvantages
Fully customizable Harder to read for beginners
Concise Slow
Works only for string elements

Try It Yourself in Our Interactive Code Shell:

So how do you apply this method to integer lists?

Method: Use the string.join() Method with Map()


The string.join(iterable) method joins together all elements in the iterable, using the string as a separator between two elements. But it expects that all elements in the iterable are already strings. If they aren’t, you need to convert them first. To achieve this, you can use the built-in map() method in Python 3.x.

# Create the Python List
lst = [1, 2, 3, 4, 5] # Use three underscores as separator
print('___'.join(map(str, lst)))
# 1___2___3___4___5 # Use arrow as separator
print('-->'.join(map(str, lst)))
# 1-->2-->3-->4-->5

The map(str, lst) method applies the function str(x) to each element x in the list. In other words, it converts each integer element to a string. An alternative way without the map(str, lst) function would be list comprehension [str(x) for x in lst] that results in the same output.


Advantages Disadvantages
Fully customizable Harder to read for beginners
Concise Slow
Works for all data types

Try It Yourself in Our Interactive Code Shell:

So, let’s finish this up!

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2020/04/...-run-code/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] List Comprehension in Python xSicKxBot 0 2,107 08-23-2023, 07:54 PM
Last Post: xSicKxBot
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 1,957 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 1,557 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,697 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Python Converting List of Strings to * [Ultimate Guide] xSicKxBot 0 1,608 05-02-2023, 01:17 PM
Last Post: xSicKxBot
  [Tut] Python Async With Statement — Simplifying Asynchronous Code xSicKxBot 0 1,343 04-28-2023, 03:04 AM
Last Post: xSicKxBot
  [Tut] Python List of Tuples to DataFrame ? xSicKxBot 0 1,513 04-22-2023, 06:10 AM
Last Post: xSicKxBot
  [Tut] Python List of Dicts to Pandas DataFrame xSicKxBot 0 1,535 04-11-2023, 04:15 AM
Last Post: xSicKxBot
  [Tut] OpenAI API – or How I Made My Python Code Intelligent xSicKxBot 0 1,283 01-25-2023, 06:53 AM
Last Post: xSicKxBot
  [Tut] Python | Split String into List of Substrings xSicKxBot 0 1,444 12-11-2022, 12:17 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016