Understanding data types is one of the most important parts of learning Python. Whether you're building a calculator, a web app, or analyzing data, everything you do involves data β and that data always has a type.
In this article, weβll dive deep into Python's data types, show real code examples with outputs, explain why each type matters, and even explore how to use arrays in Python using array
and NumPy
.
π§ What Are Data Types in Python?
In Python, a data type tells the interpreter what kind of value a variable holds β is it a number? a list? a sentence?
Python is dynamically typed, meaning you donβt have to declare data types. It figures them out when the code runs.
π 1. Numeric Types
Numeric types represent numbers, and Python supports three main numeric types:
π’ int
(Integer)
Used to store whole numbers (positive or negative) without decimal points.
x = 42
print(x) # 42
print(type(x)) # <class 'int'>
Integers can be very large in Python:
big = 12345678901234567890
print(big) # 12345678901234567890
π’ float
(Floating-point)
Represents numbers with decimal points. These are useful for measurements, scores, percentages, etc.
pi = 3.14159
print(pi) # 3.14159
print(type(pi)) # <class 'float'>
Python also supports scientific notation:
sci = 1.2e3
print(sci) # 1200.0
Note: Floats can have rounding errors due to binary representation.
π’ complex
(Complex numbers)
Stores numbers with a real and imaginary part. Mostly used in scientific computing.
z = 2 + 3j
print(z) # (2+3j)
print(z.real) # 2.0
print(z.imag) # 3.0
π 2. Text Type
str
(String)
A string is a sequence of characters. Strings are used to represent text data.
name = "Vall"
message = 'Hello, world!'
print(name) # Vall
print(type(name)) # <class 'str'>
Strings support many operations:
print(name.upper()) # VALL
print("Python"[0]) # P
print("Vall" in name) # True
f-strings are used to embed variables in strings:
age = 21
print(f"My name is {name} and I am {age} years old.")
# My name is Vall and I am 21 years old.
π 3. Sequence Types
list
A list is an ordered collection of items. It is mutable, meaning it can be changed after creation.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
tuple
A tuple is similar to a list but immutable β once created, it can't be changed.
point = (10, 20)
print(point) # (10, 20)
Attempting to modify it causes an error:
# point[0] = 15 # TypeError: 'tuple' object does not support item assignment
range
Used to generate a sequence of numbers, often in loops.
r = range(5)
print(list(r)) # [0, 1, 2, 3, 4]
π§½ 4. Set Types
set
A set is an unordered, mutable collection of unique elements. That means no duplicates are allowed, and the order is not guaranteed.
colors = {"red", "green", "blue", "red"}
print(colors) # {'green', 'red', 'blue'}
You can add or remove elements:
colors.add("yellow")
print(colors)
colors.remove("green")
print(colors)
Mathematical set operations are supported:
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # intersection: {3}
print(a | b) # union: {1, 2, 3, 4, 5}
print(a - b) # difference: {1, 2}
Sets are useful for checking membership and removing duplicates from a list:
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = set(nums)
print(unique_nums) # {1, 2, 3, 4, 5}
frozenset
A frozenset
is like a set, but immutable β once created, you can't add or remove elements. This makes it hashable and usable as a dictionary key or element in another set.
fs = frozenset([1, 2, 3, 2])
print(fs) # frozenset({1, 2, 3})
You can perform the same operations as with a set (except mutation):
fs1 = frozenset([1, 2, 3])
fs2 = frozenset([3, 4, 5])
print(fs1 & fs2) # intersection: frozenset({3})
But this will raise an error:
# fs.add(6) # AttributeError: 'frozenset' object has no attribute 'add'
Use frozenset
when you need a constant set of values that should not be changed.
ποΈ 5. Mapping Type
dict
A dictionary stores key-value pairs.
student = {
"name": "Vall",
"age": 21,
"course": "CS"
}
print(student["name"]) # Vall
student["age"] = 22
print(student)
# {'name': 'Vall', 'age': 22, 'course': 'CS'}
β¨ 6. Boolean Type
bool
Boolean values represent True
or False
. They are commonly used in conditions.
is_active = True
print(is_active) # True
print(type(is_active)) # <class 'bool'>
Expressions that return booleans:
print(10 > 5) # True
print(10 < 3) # False
β 7. None Type
NoneType
Represents the absence of a value.
x = None
print(x) # None
print(type(x)) # <class 'NoneType'>
Often used for default values or empty returns.
π Type Checking and Conversion
x = 100
print(type(x)) # <class 'int'>
print(isinstance(x, int)) # True
str_x = str(x)
print(str_x) # '100'
print(type(str_x)) # <class 'str'>
β»οΈ Mutable vs Immutable
Data Type | Mutable? |
---|---|
int , float , str , tuple , bool , None
|
β No |
list , dict , set
|
β Yes |
π Arrays in Python
Python doesnβt have a native array type like Java or C++, but we can use:
1. array
module (basic)
import array
nums = array.array('i', [1, 2, 3, 4])
print(nums) # array('i', [1, 2, 3, 4])
print(nums[0]) # 1
'i'
indicates integers. 'f'
for float, 'd'
for double.
2. NumPy Arrays (powerful & preferred for data science)
import numpy as np
arr = np.array([10, 20, 30])
print(arr) # [10 20 30]
print(arr.dtype) # int64 (platform dependent)
print(arr + 5) # [15 25 35]
NumPy arrays are faster, more efficient, and used in machine learning, AI, and data science.
Install with:
pip install numpy
π§ Mini Challenge
a = [1, 2, 3]
b = a
b.append(4)
print(a) # ?
Answer: [1, 2, 3, 4]
because both a
and b
point to the same list (mutable).
β Final Thoughts
Data types are the foundation of Python programming. Mastering them helps you:
- Store and process data effectively
- Avoid bugs
- Build real applications
From int
to dict
, from list
to NumPy
arrays β Python gives you tools to handle any kind of data.
Happy coding ππ!
Top comments (0)