Python data types represent the kind of value a variable can hold. Every value stored inside a Python variable belongs to a specific data type, and the interpreter uses this type information to determine:
- How much memory the object needs
- What operations can be performed on it
- How it behaves when used in expressions
In the previous chapter (Python Variables), you learned that variables are simply names pointing to objects stored in memory.
Each object has a type, and Python automatically assigns this type when the object is created.
Why Data Types Matter
Understanding data types is important because:
- They help you store the right kind of data (e.g., numbers vs text).
- They determine what operations are valid (e.g., you can add two numbers but cannot add a number to a string without conversion).
- They help avoid TypeErrors.
- They allow better memory optimization.
Python is a dynamically typed language, meaning:
- You do not need to declare the data type manually.
- Python decides the type automatically when you assign a value.
Example
a = 10 # integer
b = 10.5 # float
c = "Hello" # string
Behind the scenes, Python stores these values in memory with their respective types.
Built-in Data Types in Python
Python has several built-in data types grouped into categories:
| Category | Data Types |
|---|---|
| Text Type | str |
| Numeric Types | int, float, complex |
| Sequence Types | list, tuple, range |
| Mapping Type | dict |
| Set Types | set, frozenset |
| Boolean Type | bool |
| Binary Types | bytes, bytearray, memoryview |
| None Type | NoneType |
Let's explore each of them with examples.
1. Text Data Type
String (str)
A string represents a sequence of characters enclosed in quotes.
You can use:
- Single quotes (' ')
- Double quotes (" ")
- Triple quotes (''' ''' or """ """) for multi-line strings
Example
name = "Merlin Academy"
language = 'Python'
paragraph = """Python is a powerful,
easy-to-learn programming language."""
Example
Accessing characters
text = "Python"
print(text[0]) # Output: P
print(text[-1]) # Output: n
Example
Concatenation
a = "Hello "
b = "World"
print(a + b)
Example
String length
text = "Merlin"
print(len(text))
Strings are immutable, meaning you cannot change characters once created.
2. Numeric Data Types
Python supports three numeric types.
(a) Integer (int)
Represents whole numbers (positive or negative) without decimals.
Example
x = 10
y = -20
z = 0
Python integers can be arbitrarily large, only limited by system memory.
(b) Float (float)
Represents numbers with decimals.
pi = 3.14
salary = 25000.50
distance = -19.55
(c) Complex (complex)
Represents numbers with a real and imaginary part.
Format → a + bj
x = 3 + 5j
y = 2j
print(type(x)) # < class 'complex' >
3. Sequence Data Types
Sequence types store multiple items.
(a) List (list)
- Ordered
- Mutable
- Allows duplicates
- Defined using square brackets []
fruits = ["apple", "banana", "mango"]
numbers = [10, 20, 30, 40]
mixed = [1, "hello", 3.5, True]
Accessing list items
print(fruits[0]) # apple
print(fruits[-1]) # mango
Modifying lists
fruits[1] = "pear"
print(fruits)
(b) Tuple (tuple)
- Ordered
- Immutable
- Allows duplicates
- Defined using parentheses ()
Useful for fixed data.
Example
dimensions = (20, 40, 60)
colors = ("red", "green", "blue")
Because tuples are immutable, modifying elements will raise an error.
(c) Range (range)
Used for sequences of numbers, mostly in loops.
Example
r = range(5)
print(list(r)) # [0, 1, 2, 3, 4]
4. Mapping Data Type
Dictionary (dict)
- Stores data in key-value pairs
- Mutable
- Keys must be unique
Example
student = {
"name": "Zara",
"age": 20,
"course": "Python"
}
Accessing values
print(student["name"])
Modifying dictionary
student["age"] = 21
5. Set Data Types
(a) Set (set)
- Unordered
- No duplicates
- Mutable
Example
numbers = {1, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4}
(b) Frozen Set (frozenset)
Like set but immutable.
Example
fs = frozenset([1, 2, 3])
print(fs)
6. Boolean Data Type
Boolean values represent True or False.
x = True
y = False
Booleans are often used in conditions:
print(10 > 5) # True
print(3 == 9) # False
Internally:
- True = 1
- False = 0
7. Binary Data Types
Used mostly for low-level programming, images, files, or network operations.
(a) Bytes (bytes)
Immutable sequence of bytes.
x = bytes([10, 20, 30, 40])
print(x)
(b) Bytearray (bytearray)
Mutable version of bytes.
y = bytearray([10, 20, 30])
y[0] = 99
print(y)
(c) Memoryview (memoryview)
Used to access memory of binary objects without copying.
a = bytearray("Python", "utf-8")
m = memoryview(a)
print(m[0]) # 80
8. None Type
Represents absence of a value.
x = None
print(type(x)) # < class 'NoneType' >
Used to indicate:
- Empty variables
- Missing data
- Function with no return value
Checking Data Types
Use the built-in type() function:
a = 10
b = "Merlin"
c = 3.14
print(type(a))
print(type(b))
print(type(c))
Type Casting (Converting Between Data Types)
Python allows converting one data type into another.
Example
Converting numbers
x = int(3.14) # 3
y = float(10) # 10.0
z = str(100) # "100"
Example
Converting sequences
tuple_to_list = list((1, 2, 3))
list_to_set = set([1, 2, 3, 3, 4])
Dynamic typing vs Strong typing
Python is:
- Dynamically typed → type decided at runtime
- Strongly typed → invalid type operations are not allowed
x = "10"
y = 5
# print(x + y) → TypeError
Mutable vs Immutable Types
| Mutable | Immutable |
|---|---|
| list | int |
| dict | float |
| set | string |
| bytearray | tuple |
| bytes |
Mutability affects memory usage and performance.
Type Annotation (PEP 484)
Python supports optional type hints:
age: int = 20
name: str = "Zara"
salary: float = 45000.50
Used heavily in large systems.
Practice Examples
Example 1 - Using different data types
name = "Merlin"
age = 18
height = 5.7
subjects = ["Python", "Django", "AI"]
info = {"name": name, "age": age}
passed = True
print(type(name))
print(type(age))
print(type(subjects))
print(type(info))
print(type(passed))
Example 2 - Working with mutable and immutable types
a = [1, 2, 3]
b = a
b[0] = 99
print(a) # [99, 2, 3]
print(b) # [99, 2, 3]
Example 3 - Working with None
a = [1, 2, 3]
b = a
b[0] = 99
print(a) # [99, 2, 3]
print(b) # [99, 2, 3]
Example 3 - Working with None
result = None
def calculate():
pass # function has no return
print(result)
print(calculate())
Conclusion
Data types form the core building block of every Python program.
Understanding them helps you write
efficient, clean, and bug-free code.