Tutorials Python Data Types
Ch 7 / 58
Python Beginner 8 min read Chapter 7 of 58

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.

What you'll learn in this chapter
Python's complete type hierarchy — all 10 built-in types
Numeric types — int, float and complex with arithmetic
Strings — immutable sequences, indexing, slicing, 40+ methods
Boolean type — True/False and truthy/falsy values
Sequence types — list, tuple and their key differences
Set and frozenset — unique unordered collections
dict — key-value mapping, the most important data structure
NoneType — Python's null and why it matters
Type checking with type() and isinstance()
Type casting — converting between types safely
Advertisement

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:

Numeric
int · float · complex
Text
str
Boolean
bool
Sequence
list · tuple · range
Mapping
dict
Set
set · frozenset
NoneType
None
Binary
bytes · bytearray
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 —
Mutable Types
Can be changed after creation.

list, dict, set

You can add, remove or modify items without creating a new object. The object's id() stays the same.
Immutable Types
Cannot be modified in-place.

int, float, str, tuple, bool, frozenset

Any "modification" creates a brand-new object with a new id().
Python — type() and id() to see mutable vs immutable
# 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.

int
Whole numbers — no size limit
Supports decimal, binary (0b), octal (0o), hex (0x) literals. Arithmetic is always exact.
float
Decimal / fractional numbers
64-bit IEEE 754. Supports scientific notation (2.5e10). Use decimal.Decimal for exact financial math.
complex
Real + imaginary: a + bj
Access .real and .imag. Use abs() for magnitude. Used with the cmath module.
Python — int, float, complex in depth
# ── 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)
Pro tip — use Decimal for money For financial calculations, use 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.

Python — string literals, indexing, slicing
# ── 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
Best practice — always use f-strings f-strings are faster, more readable, and support expressions directly: f"Total: {price * qty:.2f}". Avoid the older % formatting and .format() in new code.
Advertisement

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.

Python — bool, truthy, falsy and boolean operators
# 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.

list — Mutable Sequence
Created with [...]
Can add, remove, or change items.
append() · insert() · pop() · sort()

Use for: shopping carts, task lists, any dynamic collection.
tuple — Immutable Sequence
Created with (...)
Cannot be modified after creation.
Faster than list · Hashable (usable as dict key).

Use for: coordinates, RGB, function return values.
Python — list and tuple operations
# ── 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.

Python — set operations and frozenset
# 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.

Python — dictionary creation, access, methods and comprehension
# ── 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'}
Pro tip — always use .get() for safe access 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.
Advertisement

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 ==.

Python — None and NoneType usage
# 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
Gotcha — mutable default arguments Never use a mutable 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().

str"42"
→
int()42
→
float()42.0
→
bool()True
Python — implicit and explicit type casting
# ── 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() vs type() — which to use? Use 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

Python — gradebook.py
# 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

Python — wordcount.py
# 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)
Chapter Summary
  • 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 — the id() 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() or decimal.Decimal for 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) == type for type checking — it respects inheritance. Wrap explicit casts in try/except ValueError for safe conversion.
⚡
Free Resource
Download the Python Data Types Cheat Sheet
All 10 types, mutable/immutable, casting functions, truthy/falsy — one printable A4 page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

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.

✓ Answer

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).

✓ Answer

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.

✓ Answer

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).

✓ Answer

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.

MCQ 1 of 4
What does type({}) return?
MCQ 2 of 4
What is the result of int(3.9)?
MCQ 3 of 4
Which of the following values is truthy in Python?
MCQ 4 of 4
How do you create an empty set in Python?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel