Data Types in Python
Every value in Python has a type — an object that tells the interpreter how to store it, what operations it supports, and how much memory it needs. Python's rich built-in type system covers numbers, text, sequences, mappings, sets and more. Understanding types deeply makes you a dramatically better Python programmer.
Python's Built-in Type System — The Big Picture
Python is an object-oriented language — everything is an object, and every object has a type. The type determines the value's behaviour: what operators it supports, which methods you can call, and how Python stores it internally. Python groups its built-in types into categories:
| Type | Category | Example Literal | Mutable? | Ordered? |
|---|---|---|---|---|
| int | Numeric |
42, -7,
0b1010
|
Immutable | — |
| float | Numeric |
3.14,
-0.5,
2e8
|
Immutable | — |
| complex | Numeric | 3+4j |
Immutable | — |
| str | Text / Sequence | "hello" |
Immutable | ✓ Yes |
| bool | Boolean (subclass int) |
True,
False
|
Immutable | — |
| list | Sequence | [1, "a", True] |
Mutable | ✓ Yes |
| tuple | Sequence | (1, "a", True) |
Immutable | ✓ Yes |
| set | Set | {1, 2, 3} |
Mutable | ✗ No |
| frozenset | Set | frozenset({1,2}) |
Immutable | ✗ No |
| dict | Mapping | {"key": "val"} |
Mutable | ✓ Python 3.7+ |
| NoneType | Null Singleton | None |
Immutable | — |
list, dict, setYou can add, remove or modify items without creating a new object. The object's
id() stays the same.
int, float, str,
tuple, bool,
frozensetAny "modification" creates a brand-new object with a new
id().
# Every Python value has a type
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type([1, 2])) # <class 'list'>
print(type({"a": 1})) # <class 'dict'>
print(type(None)) # <class 'NoneType'>
# Mutable — id() stays the same after modification
my_list = [1, 2, 3]
print(id(my_list)) # e.g. 140234567890
my_list.append(4)
print(id(my_list)) # same id — same object
# Immutable — new id() after every "change"
x = "hello"
print(id(x)) # e.g. 140234567000
x = x + " world"
print(id(x)) # different id — brand new object
Numeric Types — int, float and complex
Python has three numeric types. int handles whole numbers
with unlimited precision (no overflow!),
float handles decimals using IEEE 754 double precision, and
complex handles numbers with real and imaginary parts.
0b), octal (0o), hex (0x)
literals. Arithmetic is always exact.
2.5e10).
Use decimal.Decimal for exact financial math.
.real and
.imag. Use
abs() for magnitude. Used with the
cmath module.
# ── int — unlimited precision integers ────────────────────────
age = 25
big_num = 10_000_000 # underscores for readability
binary = 0b1010 # 10 — binary literal
octal = 0o17 # 15 — octal literal
hexa = 0xFF # 255 — hex literal
print(2 ** 100) # 1267650600228229401496703205376 (no overflow!)
print(17 // 3) # 5 — floor division
print(17 % 3) # 2 — modulo (remainder)
print(17 / 3) # 5.666… (/ always returns float)
# ── float — decimal numbers ────────────────────────────────────
pi = 3.14159
science = 2.5e10 # 25,000,000,000.0
# Floating-point trap — always round for display
print(0.1 + 0.2) # 0.30000000000000004 ← IEEE 754 issue
print(round(0.1 + 0.2, 2)) # 0.3 ← correct for display
# ── complex — real + imaginary ─────────────────────────────────
z1 = 3 + 4j
z2 = 1 - 2j
print(z1.real) # 3.0
print(z1.imag) # 4.0
print(abs(z1)) # 5.0 (magnitude = √(3²+4²))
print(z1 + z2) # (4+2j)
from decimal import Decimal.
Decimal("0.1") + Decimal("0.2") gives exactly
0.3 — no floating-point surprises.
Strings — Immutable Text Sequences
A string (str) is an ordered,
immutable sequence of Unicode characters. Strings support indexing, slicing, and over
40 built-in methods. They are one of the most-used types in all Python programs.
# ── String literals — four ways ────────────────────────────────
s1 = 'single quotes'
s2 = "double quotes"
s3 = """Triple quotes span
multiple lines"""
s4 = r"raw\nstring" # raw — backslash is literal
# ── Indexing — zero-based, negative works too ──────────────────
word = "Python"
print(word[0]) # P (first character)
print(word[-1]) # n (last character)
print(word[-3]) # h (3rd from end)
# ── Slicing — [start : stop : step] ───────────────────────────
print(word[0:3]) # Pyt
print(word[2:]) # thon
print(word[:4]) # Pyth
print(word[::-1]) # nohtyP (reversed!)
# ── Common string methods ──────────────────────────────────────
text = " Hello, Python! "
print(text.strip()) # "Hello, Python!"
print(text.lower()) # " hello, python! "
print(text.upper()) # " HELLO, PYTHON! "
print(text.replace("Python", "World")) # " Hello, World! "
print(text.split(",")) # [' Hello', ' Python! ']
print(text.find("Python")) # 9 (index where it starts)
print("-".join(["a", "b", "c"])) # "a-b-c"
# ── f-strings — modern string formatting (Python 3.6+) ─────────
name = "Alice"
score = 95.678
print(f"Name: {name}") # Name: Alice
print(f"Score: {score:.2f}") # Score: 95.68
print(f"Upper: {name.upper()}") # Upper: ALICE
f"Total: {price * qty:.2f}". Avoid the older
% formatting and
.format() in new code.
Boolean — True, False and Truthy/Falsy Values
bool is a subclass of int in Python.
True is literally 1 and
False is 0. Every Python
object has a boolean value — this concept of truthy and falsy is used in every
if statement.
# bool is a subclass of int
print(isinstance(True, int)) # True
print(True + 1) # 2
print(False + 5) # 5
# ── Falsy values — evaluate to False in boolean context ────────
# False, 0, 0.0, 0j, "", [], (), {}, set(), None
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool(None)) # False
# ── Truthy — everything else ───────────────────────────────────
print(bool(1)) # True
print(bool("hello")) # True
print(bool([0])) # True (non-empty list)
# Short-circuit boolean operators
print(True and False) # False
print(True or False) # True
print(not True) # False
# Practical pattern — default value with "or"
name = ""
label = name or "Anonymous"
print(label) # Anonymous (because "" is falsy)
Sequence Types — list and tuple
Both list and tuple are
ordered sequences that can store mixed types. The critical difference:
lists are mutable (you can change them),
tuples are immutable (frozen after creation). Use tuples for data that must not
change — coordinates, RGB colours, database records.
[...]Can add, remove, or change items.
append() ·
insert() ·
pop() · sort()Use for: shopping carts, task lists, any dynamic collection.
(...)Cannot be modified after creation.
Faster than list · Hashable (usable as dict key).
Use for: coordinates, RGB, function return values.
# ── List — creation, indexing, modifying ───────────────────────
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
fruits.append("date") # add to end
fruits.insert(1, "avocado") # insert at index 1
fruits.remove("banana") # remove first match
popped = fruits.pop() # remove & return last item
nums = [3, 1, 4, 1, 5, 9]
nums.sort() # [1, 1, 3, 4, 5, 9] in-place
print(sum(nums), min(nums), max(nums)) # 23 1 9
# List comprehension — Pythonic way to build lists
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# ── Tuple — immutable sequence ─────────────────────────────────
coords = (10.5, 20.3)
rgb = (255, 128, 0)
singleton = (42,) # ← comma required for single-element!
# Tuple unpacking — very Pythonic
x, y = coords
r, g, b = rgb
print(f"R={r} G={g} B={b}") # R=255 G=128 B=0
Set & frozenset — Unique Unordered Collections
A set is an
unordered collection of unique elements. Duplicates are automatically removed.
Sets excel at membership testing (O(1) lookup), removing duplicates, and mathematical set
operations. frozenset is the immutable, hashable version.
# Creating sets — duplicates removed automatically
nums = {1, 2, 3, 2, 1}
print(nums) # {1, 2, 3}
empty_set = set() # ← {} creates an empty DICT, not set!
# Practical: remove duplicates from a list
tags = ["python", "code", "python", "tips"]
unique = list(set(tags))
print(unique) # ['code', 'python', 'tips']
# Fast membership test O(1)
allowed = {"admin", "editor", "viewer"}
print("admin" in allowed) # True
# Set math operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # {1,2,3,4,5,6} union
print(A & B) # {3,4} intersection
print(A - B) # {1,2} difference
print(A ^ B) # {1,2,5,6} symmetric difference
# frozenset — immutable, can be a dict key
frozen = frozenset({1, 2, 3})
lookup = {frozen: "group A"} # frozenset is hashable!
Dictionary — Key-Value Mapping
A dict is an ordered (Python 3.7+),
mutable mapping of unique keys to values. It is arguably the most important
data structure in Python — JSON data, function keyword arguments, configuration, caching are all
built on dicts. Keys must be hashable.
# ── Creating dicts ─────────────────────────────────────────────
person = {
"name": "Alice",
"age": 28,
"city": "Vadodara",
"scores": [90, 85, 92]
}
config = dict(host="localhost", port=8080, debug=True)
# ── Access ─────────────────────────────────────────────────────
print(person["name"]) # Alice
print(person.get("phone", "N/A")) # N/A (safe — no KeyError)
# ── Add / update / delete ──────────────────────────────────────
person["email"] = "alice@email.com" # add new key
person["age"] = 29 # update existing key
del person["city"] # delete key
# ── Iterate ────────────────────────────────────────────────────
for key, value in person.items():
print(f"{key}: {value}")
# ── Dict comprehension ─────────────────────────────────────────
squares = {x: x ** 2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# ── Merge dicts (Python 3.9+) ──────────────────────────────────
defaults = {"theme": "dark", "lang": "en"}
user_prefs = {"theme": "light"}
merged = defaults | user_prefs # {'theme': 'light', 'lang': 'en'}
person["phone"] raises a
KeyError if the key is missing.
person.get("phone", "N/A") returns a safe default. Use
.get() whenever a key might not exist.
NoneType — Python's Null Value
None is Python's null — a singleton object of type
NoneType. It represents the absence of a value.
Functions that don't explicitly return something return
None. Always compare
None using is, never
==.
# None is a singleton — only one instance exists
x = None
print(type(x)) # <class 'NoneType'>
print(x is None) # True ← always use "is" not "=="
# Function with no return → returns None
def greet(name):
print(f"Hello, {name}!")
result = greet("Bob")
print(result) # None
# None as a safe optional default
def find_user(user_id, db=None):
if db is None:
db = {}
return db.get(user_id) # returns None if not found
# None is falsy
print(bool(None)) # False
val = None
print(val or "default") # default
def fn(lst=[]): — the list is
created once and shared across all calls. Use None as
sentinel: def fn(lst=None): if lst is None: lst = []
Type Casting — Converting Between Types
Type casting converts a value from one type to another. Python provides
built-in functions: int(),
float(), str(),
bool(), list(),
tuple(), set().
# ── Implicit casting (Python does it automatically) ────────────
result = 5 + 2.0 # int + float → float (7.0)
result = True + 3 # bool + int → int (4)
# ── To int ─────────────────────────────────────────────────────
print(int(3.9)) # 3 (truncates, does NOT round!)
print(int("42")) # 42
print(int("0xFF", 16)) # 255 (parse hex string)
print(int(True)) # 1
# ── To float ───────────────────────────────────────────────────
print(float(7)) # 7.0
print(float("3.14")) # 3.14
print(float("inf")) # inf
# ── To str ─────────────────────────────────────────────────────
print(str(100)) # "100"
print(str([1, 2, 3])) # "[1, 2, 3]"
# ── Sequence conversions ───────────────────────────────────────
my_list = [1, 2, 3, 2, 1]
my_tuple = tuple(my_list) # (1, 2, 3, 2, 1)
my_set = set(my_list) # {1, 2, 3} duplicates removed
chars = list("hello") # ['h','e','l','l','o']
# ── Error-safe casting with try/except ─────────────────────────
user_input = "abc"
try:
number = int(user_input)
except ValueError:
print(f"'{user_input}' is not a valid integer")
# 'abc' is not a valid integer
isinstance(x, int) in production — it respects
inheritance (bool is a subclass of
int, so
isinstance(True, int) is
True). Use
type(x) == int only when you need an exact type match.
Mini Projects — Apply What You've Learned
Project 1 — Student Grade Book
# Student Grade Book — dict, list, str, float, round()
students = {
"Alice": [85, 92, 78, 96, 88],
"Bob": [70, 65, 80, 75, 72],
"Carol": [95, 98, 92, 100, 97],
}
def get_grade(avg):
if avg >= 90: return "A"
elif avg >= 80: return "B"
elif avg >= 70: return "C"
else: return "F"
print(f"{'Name':10} {'Average':>8} {'Grade':>6}")
print("─" * 28)
for name, scores in students.items():
avg = round(sum(scores) / len(scores), 1)
grade = get_grade(avg)
print(f"{name:10} {avg:>8} {grade:>6}")
# Name Average Grade
# ────────────────────────────
# Alice 87.8 B
# Bob 72.4 C
# Carol 96.4 A
Project 2 — Word Frequency Counter
# Word Frequency Counter — str, list, dict, set, sorted()
import string
text = """Python is great. Python is easy to learn.
Learning Python is fun and rewarding!"""
words = text.lower().translate(
str.maketrans("", "", string.punctuation)
).split()
# Count using dict
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(f"Total: {len(words)} Unique: {len(set(words))}")
for word, count in sorted(freq.items(), key=lambda x: -x[1])[:5]:
print(f" {word:12} {'█' * count} ({count})")
# Total: 12 Unique: 8
# python ████ (4)
# is ███ (3)
# learning █ (1)
# easy █ (1)
-
Python has 10 built-in data types grouped as: numeric (
int,float,complex), text (str), boolean (bool), sequence (list,tuple), set (set,frozenset), mapping (dict), and null (NoneType). -
Mutable types (
list,dict,set) can be changed in place — theid()stays the same. Immutable types (int,str,tuple) create new objects on every "change". -
int has unlimited precision — no overflow. float uses IEEE
754 — always use
round()ordecimal.Decimalfor financial math. -
str is immutable. Use
f"..."f-strings for formatting, indexing and slicing for access, and the rich method library (split,join,strip, etc.) for manipulation. -
bool is a subclass of int —
True == 1,False == 0. Every object is truthy or falsy. Falsy:0,"",[],{},None. - list is mutable and ordered. Use for collections you'll modify. tuple is immutable and hashable — use for fixed data and as dict keys.
- set gives O(1) membership testing and automatic duplicate removal. Use frozenset when you need a hashable set (e.g., as a dict key).
-
dict is the workhorse of Python. Always use
.get(key, default)for safe access. Use dict comprehensions for clean data transformation. -
None is a singleton. Always compare with
is None, never== None. Use it as a safe default parameter sentinel instead of mutable defaults. -
Use isinstance(x, type) over
type(x) == typefor type checking — it respects inheritance. Wrap explicit casts intry/except ValueErrorfor safe conversion.
Mutable types (list,
dict,
set) can be modified in place after creation
— their id() stays the same even after
changes. Immutable types (int,
float,
str,
tuple,
bool,
frozenset) cannot be changed in place — any
"modification" creates a brand-new object with a new
id().
Immutability matters for safety (you can pass an immutable to a function knowing it won't be changed), for dictionary keys (keys must be hashable, which requires immutability), and for Python's internal optimisations like string interning.
This is a classic IEEE 754 floating-point precision issue. In binary,
0.1 and
0.2 cannot be represented exactly — they are
infinite repeating fractions. When Python adds them, the result is
0.30000000000000004, not exactly
0.3.
Solutions: Use round(0.1 + 0.2, 2) == 0.3,
or math.isclose(0.1 + 0.2, 0.3), or
from decimal import Decimal for exact
arithmetic (required for financial applications).
None is a singleton — there
is exactly one None object in all of Python.
is checks identity (same object in
memory), while == checks equality,
which can be overridden by custom classes. A custom class could define
__eq__ to make
obj == None return
True even when
obj is not
None. Using
is None is always safe, explicit, and
Pythonic.
Tuple: Yes. List: No. Dictionary keys must be hashable. To be hashable, an object must have a consistent hash value throughout its lifetime — which requires it to be immutable.
Tuples are immutable, so their hash is fixed. Lists are mutable — if you could
use a list as a key and then modify the list, the key would no longer be
findable. Python therefore raises a
TypeError: unhashable type: 'list'. The same
rule applies to sets (unhashable) vs frozensets (hashable).
type(x) == int checks for an
exact match — it returns
False if
x is an instance of a subclass of
int.
isinstance(x, int) returns
True if
x is an
int or any subclass of
int. Since
bool is a subclass of
int,
isinstance(True, int) returns
True but
type(True) == int returns
False. Always prefer
isinstance() for type checking in production
code — it respects Python's inheritance hierarchy.
type({}) return?int(3.9)?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.