Printing a list directly gives you Python’s own representation, brackets and all:
fruits = ["apple", "banana", "mango"]
print(fruits) # ['apple', 'banana', 'mango']Useful for debugging, ugly for anything a person reads. Here is every other way, and when each is right.
Joined into a sentence#
print(", ".join(fruits)) # apple, banana, mango
print(" | ".join(fruits)) # apple | banana | mangoThe separator goes first and join is called on it, which reads backwards until you have done it a few times.
One per line#
for fruit in fruits:
print(fruit)
print("\n".join(fruits)) # same output, one call
print(*fruits, sep="\n") # unpack into print's argumentsThat last form is worth knowing: *fruits passes each item as a separate argument, and sep controls what goes between them.
Numbered#
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. mangostart=1 because people count from one even though lists do not.
Aligned columns#
scores = [("Ada", 91), ("Sam", 7), ("Kai", 145)]
for name, score in scores:
print(f"{name:<10} {score:>5}")
# Ada 91
# Sam 7
# Kai 145<10 pads to ten characters on the left, >5 right-aligns in five. That is what makes numbers line up on their last digit.
A list of dictionaries#
people = [
{"name": "Ada", "role": "Engineer"},
{"name": "Sam", "role": "Designer"},
]
width = max(len(p["name"]) for p in people)
for p in people:
print(f"{p['name']:<{width}} {p['role']}")Measuring the widest value first means the columns fit the data rather than a number you guessed.
Readable nested data#
from pprint import pprint
data = {"users": [{"name": "Ada", "tags": ["admin", "dev"]}]}
print(data) # one long unreadable line
pprint(data) # indented and wrappedFor JSON-shaped data, json.dumps is even clearer:
import json
print(json.dumps(data, indent=2))Only part of a long list#
big = list(range(1000))
print(big[:5]) # first five
print(big[-5:]) # last five
print(f"{len(big)} items, first 3: {big[:3]}")Questions people ask#
Why does my list print with quotes around the strings?
Printing the list itself shows Python’s repr of each item, which includes quotes. Loop over it or use join to print the values themselves.
How do I print without a newline?
print(item, end=" "). The default end is a newline.
How do I print a list to a file?
print(*items, sep="\n", file=f) inside a with open(...) block. See reading and writing files.