Basics
Literals
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.0Integer 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 1000000String 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=98Container 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
EllipsisCurly-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
setNotes
- Literals are good for small local values; constants are better for repeated values with meaning.
{}is an empty dictionary. Useset()for an empty set.- Bytes literals are binary data; string literals are Unicode text.
...evaluates to theEllipsisobject.
See also
- value surface: Values
- text literal: Strings
- related: Numbers
- next depth: String Formatting
Run the complete example
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.