iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Data Types

Python comes with a small set of built-in types covering numbers, text, collections, and a "no value" sentinel.

The built-ins

TypeExampleUse for
int42Whole numbers; unlimited size.
float3.14Decimal numbers (binary IEEE-754).
complex2 + 3jComplex numbers — science, signal processing.
boolTrue / FalseLogic. Subclass of int (True == 1).
str'hello'Unicode text.
bytesb'\\xff'Raw binary data.
list[1, 2, 3]Ordered, mutable.
tuple(1, 2)Ordered, immutable.
set{1, 2, 3}Unordered, unique.
dict{'a': 1}Key→value mapping. Insertion-ordered.
NoneTypeNone"No value" sentinel.

Mutable vs immutable

Mutable (can change in place)Immutable
list, dict, set, custom classesint, float, str, tuple, bool, None, frozenset

Checking type

PYTHON
x = 42
print(type(x))             # <class 'int'>
print(isinstance(x, int))  # True
print(isinstance(x, (int, float)))   # True
Tip: Prefer isinstance(x, T) over type(x) is T. It respects subclasses, so it doesn't break when someone passes a subtype.

Example

Example
examples = {
    'int':   1,
    'float': 3.14,
    'str':   'hello',
    'bool':  True,
    'list':  [1, 2, 3],
    'tuple': (1, 2),
    'dict':  {'a': 1},
    'set':   {1, 2, 3},
    'none':  None,
}
for k, v in examples.items():
    print(k, type(v).__name__, v)
Try it Yourself »

Exercise

Which built-in returns the type of an object?

(x)

Test yourself

Q1. Which is NOT a built-in type?
Q2. Which is immutable?
Q3. Preferred type test is…

Discussion

Loading…