Python Data Types
Learn about the different data types available in Python and how to use them.
Built-in Data Types
In programming, data type is an important concept. Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type
strNumeric Types
int, float, complexSequence Types
list, tuple, rangeMapping Type
dictSet Types
set, frozensetBoolean Type
boolBinary Types
bytes, bytearray, memoryviewNone Type
NoneTypeGetting the Data Type
You can get the data type of any object by using the type() function:
Example
x = 5
print(type(x))Setting the Data Type
In Python, the data type is set when you assign a value to a variable:
Example
x = "Hello World"Data Type: str
Example
x = 20Data Type: int
Example
x = 20.5Data Type: float
Example
x = 1jData Type: complex
Example
x = ["apple", "banana", "cherry"]Data Type: list
Example
x = ("apple", "banana", "cherry")Data Type: tuple
Example
x = range(6)Data Type: range
Example
x = {"name" : "John", "age" : 36}Data Type: dict
Example
x = {"apple", "banana", "cherry"}Data Type: set
Example
x = frozenset({"apple", "banana", "cherry"})Data Type: frozenset
Example
x = TrueData Type: bool
Example
x = b"Hello"Data Type: bytes
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
Example
x = str("Hello World")Data Type: str
Example
x = int(20)Data Type: int
Example
x = float(20.5)Data Type: float
Example
x = complex(1j)Data Type: complex
Example
x = list(("apple", "banana", "cherry"))Data Type: list
Example
x = tuple(("apple", "banana", "cherry"))Data Type: tuple
Example
x = range(6)Data Type: range
Example
x = dict(name="John", age=36)Data Type: dict
Example
x = set(("apple", "banana", "cherry"))Data Type: set
Example
x = frozenset(("apple", "banana", "cherry"))Data Type: frozenset
Example
x = bool(5)Data Type: bool
Example
x = bytes(5)Data Type: bytes
Mutable vs Immutable
This is the most important distinction between the built-in types. Immutable objects cannot be changed after creation; mutable ones can.
| Immutable | Mutable |
|---|---|
| int, float, bool, complex | list |
| str | dict |
| tuple, frozenset | set |
| bytes | bytearray |
s = "hello"
# s[0] = "H" # TypeError: strings are immutable
s = "H" + s[1:] # make a NEW string instead
print(s) # Hello
nums = [1, 2, 3]
nums[0] = 99 # lists are mutable
print(nums) # [99, 2, 3]Check a Type
x = 3.14
print(type(x)) # <class 'float'>
print(isinstance(x, float)) # True
print(isinstance(x, (int, float))) # True -> any of thesePrefer isinstance(x, int) over type(x) == int — isinstance also accepts subclasses and a tuple of types.
Try It Yourself
Exercise 1: Print the type of True, 10, "10", and [10].
Show solution
for v in (True, 10, "10", [10]):
print(type(v))
# bool, int, str, listExercise 2: Is a tuple mutable or immutable? Prove it in code.
Show solution
t = (1, 2, 3)
# t[0] = 9 # TypeError -> tuples are immutable
print("immutable")Key Takeaways
- Python has numeric, text, sequence, mapping, set, boolean, and binary types.
- Immutable objects (str, tuple, int) cannot change in place; mutable ones (list, dict, set) can.
- Use
type()to inspect andisinstance()to test types.
📘 Real-World Deep Dive
Choosing the right built-in type (<code>set</code> vs <code>list</code>, <code>tuple</code> vs <code>namedtuple</code>, <code>int</code> vs <code>Decimal</code>) is the single biggest lever on both correctness and performance.
Real-Life Scenario
A de-duplication + aggregation pipeline on a million-row CSV — the right types turn a slow script into a 2-second one.
Real-Life Example
import csv
from collections import Counter, defaultdict
from decimal import Decimal
seen_ids: set[str] = set()
totals: defaultdict[str, Decimal] = defaultdict(lambda: Decimal("0"))
with open("orders.csv", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
if row["order_id"] in seen_ids:
continue # set lookup ⇒ O(1)
seen_ids.add(row["order_id"])
totals[row["product"]] += Decimal(row["amount"])
top = Counter(totals).most_common(3)
print("Top 3 products by revenue:")
for product, amount in top:
print(f" {product}: {amount}")Expected Output
Top 3 products by revenue:
mug: 1823.40
shirt: 970.00
cap: 412.10Common mistakes
- Using a
listfor membership tests is O(n) — switch tosetfor membership,dictfor lookup. floatcannot safely represent money — every finance check should usedecimal.Decimalor store integer cents.- Mixing
strIDs that look like ints ("0010") loses leading zeros; convert intentionally.
🚀 Performance & Best Practices
setlookups anddictlookups are amortised O(1); lists are O(n).intarithmetic is ~50× faster thanDecimal— store money as cents (e.g.int) when correctness allows.- Use
dataclassesortyping.NamedTupleinstead of free-formdicts in hot paths to make intent explicit.
🧪 Try It Yourself
- Benchmark the example above using
listinstead ofset— record the slowdown. - Convert amounts to integer cents and re-run — note the precision plus the speedup.
- Replace
defaultdict(lambda: Decimal("0"))with aCounterafter adjusting precision.