Say Goodbye to Brackets! Learn How to Print List Elements Beautifully in Python.

Discover simple yet powerful techniques to print list elements without the default brackets, making your output cleaner and more readable. …

Updated August 26, 2023



Discover simple yet powerful techniques to print list elements without the default brackets, making your output cleaner and more readable.

Let’s face it – when you print a list in Python, those square brackets tend to get in the way. They’re essential for defining lists, but they can make your output look cluttered, especially if you’re dealing with large datasets.

Imagine wanting to display a shopping list neatly, but instead of seeing:

['apples', 'bananas', 'milk']

You get:

apples
bananas
milk

Much nicer, right? That’s exactly what we’ll learn to do in this article.

Understanding the Problem

Python lists are ordered collections of items enclosed within square brackets []. When you use the print() function on a list, it displays the entire list structure, including those brackets. While this is technically correct, it often makes the output less user-friendly.

The Solution: Looping Through Lists

The key to removing brackets lies in iterating through each element of the list individually and printing them one by one. We can achieve this using a for loop.

Step 1: Create your list

shopping_list = ['apples', 'bananas', 'milk']

Step 2: Use a for loop to iterate through each item in the list.

for item in shopping_list:
  print(item)

Let’s break down this code:

  • for item in shopping_list:: This line starts the loop. It says, “For every item inside the shopping_list, do the following…”

  • print(item): Inside the loop, we simply print the current item. Since we’re not enclosing it in any brackets, the output will be clean and readable.

Output:

apples
bananas
milk

Additional Tips:

  • Joining Elements with a Separator: Want to display your list elements on a single line separated by a comma or space? Use the join() method:

    print(', '.join(shopping_list)) 
    # Output: apples, bananas, milk
    
  • Formatting for Readability: For larger lists, consider adding indentation to improve readability.

Let me know if you’d like to explore other ways to manipulate and display list data in Python!


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp