Basics

Literals

Literals write values directly in Python source code.

Numeric literals write numbers directly. Complex literals use j for the imaginary part.

Source

whole = 42
fraction = 3.5
complex_number = 2 + 3j
print(whole, fraction, complex_number.imag)

Output

42 3.5 3.0
int42 · 0x2a · 0b101float3.14 · 1e-3str"hi" · 'hi'list[1, 2, 3]dict{k: v}set{1, 2, 3}
Each Python type has its own literal spellings; ints accept decimal, hex, and binary; strings accept either quote.

Integer literals also accept hexadecimal (0x), binary (0b), and octal (0o) prefixes. Underscores group digits visually without changing the value.

Source

flags = 0xFF
mask = 0b1010
million = 1_000_000
print(flags, mask, million)

Output

255 10 1000000

String literals write Unicode text. Raw strings keep backslashes literal, bytes literals write binary data rather than text, and f-strings (f"...") embed expressions inline.

Source

text = "python"
raw_pattern = r"\d+"
data = b"py"
score = 98
formatted = f"score={score}"
print(text)
print(raw_pattern)
print(data)
print(formatted)

Output

python
\d+
b'py'
score=98

Container literals create tuples, lists, dictionaries, and sets. Each container answers a different question about order, position, lookup, or uniqueness.

Source

point = (2, 3)
names = ["Ada", "Grace"]
scores = {"Ada": 98}
unique = {"py", "go"}
print(point)
print(names[0])
print(scores["Ada"])
print(sorted(unique))

Output

(2, 3)
Ada
98
['go', 'py']

True, False, None, and ... are singleton literal-like constants used for truth values, absence, and placeholders.

Source

print(True, False, None)
print(...)

Output

True False None
Ellipsis

Curly-brace literals are dictionaries by default. The empty form {} is an empty dictionary, not an empty set; use set() for that. A non-empty {1, 2} is a set because keyless items can only be a set.

Source

print(type({}).__name__)
print(type(set()).__name__)
print(type({1, 2}).__name__)

Output

dict
set
set

Notes

See also

Run the complete example

Example code

Expected output

42 3.5 3.0
255 10 1000000
python
\d+
b'py'
score=98
(2, 3)
Ada
98
['go', 'py']
True False None
Ellipsis
dict
set
set

Execution time appears here after you run the example.