Ditch the Brackets

Learn how to display your Python lists without those pesky brackets, making your output cleaner and more readable. …

Updated August 26, 2023



Learn how to display your Python lists without those pesky brackets, making your output cleaner and more readable.

Python lists are incredibly versatile, allowing you to store collections of items like numbers, words, or even other lists. When you print a list directly, Python displays it within square brackets []. While this is technically correct, sometimes you want a more visually appealing output, especially when presenting data.

Let’s explore how to achieve this “bracket-free” printing and why it matters.

Why Print Lists Without Brackets?

Imagine you have a list of ingredients for a recipe:

ingredients = ['flour', 'sugar', 'eggs', 'milk']
print(ingredients) 

This will output:

['flour', 'sugar', 'eggs', 'milk']

It’s functional, but the brackets make it look less like a natural ingredient list. Removing them enhances readability, especially when displaying lists to users or incorporating them into reports.

Methods for Bracket-Free Printing

Here are the common approaches:

  1. Looping through the List:

    ingredients = ['flour', 'sugar', 'eggs', 'milk']
    for item in ingredients:
        print(item, end=" ") 
    

    This code iterates through each element (item) in the ingredients list. The print(item, end=" ") statement prints each item followed by a space instead of a newline.

  2. Joining List Elements:

    ingredients = ['flour', 'sugar', 'eggs', 'milk']
    print(", ".join(ingredients))
    

    This method uses the join() function, which takes a separator (in this case “, “) and combines all list elements into a single string.

Choosing the Right Method:

  • Use looping if you want more control over formatting (e.g., adding commas after every element except the last one).
  • Use joining for simplicity when a specific separator works well.

Let’s illustrate with a practical example:

shopping_list = ['apples', 'bananas', 'bread', 'cheese']

# Using looping
print("Here's your shopping list:")
for item in shopping_list:
    print(item)

# Using joining 
print("\nRemember to buy:")
print(", ".join(shopping_list))

This code demonstrates both methods, producing a clean and user-friendly shopping list output.

Key Takeaways:

  • Printing lists without brackets enhances readability.
  • Looping provides flexibility for custom formatting.
  • Joining is concise when a simple separator suits your needs.

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

Intuit Mailchimp