Open In App

Print lists in Python

Last Updated : 17 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Printing a list in Python is a common task when we need to visualize the items in the list. There are several methods to achieve this and each is suitable for different situations. In this article we explore these methods.

The simplest way of printing a list is directly with the print() function:

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

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

Note: This method prints the raw Python list syntax (as a single object), including the brackets and commas.

If we want a more cleaner or customized output format then please follow the below discussed approach.

Using print() with * operator

We can use print(*list_name) when we want a simple and clean display of list elements without additional formatting like brackets or commas. The * operator unpacks the list so that each element is printed individually.

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

# Print without using any separators
# between elements
print(*a)

# Print using separator (,)
print(*a, sep =', ')

Output
1 2 3 4 5
1, 2, 3, 4, 5

Explanation: The * operator unpacks the list and pass its elements as separate arguments to print(). By using sep, we can specify custom separators such as (,).

Using a Loop

We can use a loop (for loop) to iterate over each elements of the list and print it. This approach provides complete control over how each element is printed.

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

# Iterate over each element of list
for val in a:
    print(val, end=' ')

Output
1 2 3 4 5 

Explanation: The end=’ ‘ ensures that each element is printed on the same line separated by a space.

Using .join()

If we have a list of strings and we want to print our list as a string where all elements are neatly joined together with a specific separator (e.g., commas or hyphens) then we can use .join() to achieve this. This method works best when print list of strings.

a = ["Geeks", "for", "Geeks"]
print(' '.join(a))

Output
Geeks for Geeks

Using map() with .join()

If our list contains mixed data types (like integers and strings) then we need to convert each element to a string before joining them. By using map(), we can efficiently apply the conversion to every item in the list in a clear and simple manner.

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

Output
1 2 3 4 5

Explanation: The map() function applies str() to each element, allowing easy conversion for join().

Which method to choose?

  • print(*lst): Clean, simple, bracket-free output.
  • .join(): For formatted output of list of string elements.
  • for loop: Full control over iteration and custom formatting.
  • map() with .join(): Handles mixed types for formatted output.
  • print(lst): Best for debugging, shows list with brackets.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg