Data Types in Python: A Complete Guide with Examples
Python is one of the most versatile and beginner-friendly programming languages, largely due to its intuitive handling of different kinds of data. That's why understanding data types in Python is fundamental for anyone looking to write efficient and error-free code. Here's the thing — every variable in Python has a specific data type that determines the kind of operations it can perform and the values it can hold. Whether you're storing a simple number, a sentence, or a complex dataset, Python's built-in data types provide the foundation for all your programming needs.
Introduction to Data Types in Python
A data type defines the nature of the data a variable can hold and the operations that can be performed on it. Python is dynamically typed, meaning you don't need to declare the type of a variable explicitly—the interpreter automatically assigns the type based on the value assigned to it. This flexibility makes Python easy to learn, but it also means you must understand how different types behave to avoid unexpected errors.
Python's core data types include:
- Numeric types:
int,float,complex - Text type:
str - Sequence types:
list,tuple,range - Mapping type:
dict - Set types:
set,frozenset - Boolean type:
bool - Binary types:
bytes,bytearray,memoryview
Let's explore each of these in detail with practical examples.
Numeric Data Types
Integer (int)
Integers are whole numbers without a decimal point. So they can be positive, negative, or zero. In Python, integers have unlimited precision, meaning they can grow as large as your system's memory allows That's the whole idea..
age = 25
temperature = -5
population = 7800000000
print(type(age)) # Output:
print(type(population)) # Output:
Float (float)
Floats represent real numbers that include a fractional component. They're ideal for measurements, scientific calculations, and financial computations.
price = 19.99
pi = 3.14159
gravity = 9.8
print(type(price)) # Output:
Complex Numbers (complex)
Complex numbers consist of a real part and an imaginary part, written as real + imaginaryj. They're used in advanced mathematics and engineering applications.
impedance = 5 + 3j
frequency = 2.5e3 + 1j
print(type(impedance)) # Output:
Text Data Type: String (str)
Strings represent text data—words, sentences, or any sequence of characters enclosed in quotes. You can use single quotes, double quotes, or triple quotes for multi-line strings.
name = "Alice"
greeting = 'Hello, World!'
message = """This is a
multi-line string."""
print(type(name)) # Output:
Strings support various operations like slicing, concatenation, and formatting:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
Sequence Data Types
List (list)
Lists are ordered, mutable collections that can hold multiple items. They're defined using square brackets [] and allow duplicate values.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.5, True]
print(fruits[0]) # Output: apple
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
Lists are highly flexible—you can add, remove, or modify elements after creation.
Tuple (tuple)
Tuples are similar to lists but are immutable, meaning once created, their elements cannot be changed. They use parentheses () That alone is useful..
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_element = (42,) # Note the comma for single-element tuples
print(coordinates[0]) # Output: 10
# coordinates[0] = 15 # This would raise a TypeError
Tuples are often used for fixed data like dates, coordinates, or database records.
Range (range)
The range type generates a sequence of numbers, commonly used in loops. It's memory-efficient because it generates values on demand rather than storing them all at once Not complicated — just consistent..
numbers = range(5)
print(list(numbers)) # Output: [0, 1, 2, 3, 4]
even_numbers = range(0, 10, 2)
print(list(even_numbers)) # Output: [0, 2, 4, 6, 8]
Mapping Data Type: Dictionary (dict)
Dictionaries store data as key-value pairs, making them perfect for structured data. Keys must be unique and immutable, while values can be of any type.
student = {
"name": "Emma",
"age": 22,
"courses": ["Math", "Physics"]
}
print(student["name"]) # Output: Emma
student["grade"] = "A"
print(student) # Output: {'name': 'Emma', 'age': 22, 'courses': ['Math', 'Physics'], 'grade': 'A'}
Dictionaries are incredibly useful for representing real-world objects and configurations.
Set Data Types
Set (set)
Sets are unordered collections of unique elements. They're defined using curly braces {} and are useful for removing duplicates or performing mathematical operations.
unique_numbers = {1, 2, 3, 3, 2, 1}
print(unique_numbers) # Output: {1, 2, 3}
unique_numbers.add(4)
unique_numbers.remove(1)
print(unique_numbers) # Output: {2, 3, 4}
Frozenset (frozenset)
A frozenset is an immutable version of a set. Once created, you cannot add or remove elements Not complicated — just consistent..
frozen = frozenset([1, 2, 3])
print(frozen) # Output: frozenset({1, 2, 3})
# frozen.add(4) # This would raise an AttributeError
Boolean Data Type (bool)
Booleans represent truth values: True or False. They're essential for conditional logic and comparisons Most people skip this — try not to..
is_logged_in = True
has_permission = False
if is_logged_in:
print("Welcome back!")
result = 5 > 3
print(result) # Output: True
Binary Data Types
Bytes (bytes)
Bytes represent immutable sequences of integers in the range 0–255. They're commonly used when working with binary files or network protocols Easy to understand, harder to ignore..
data = b"Hello"
print(data[0]) # Output: 72 (ASCII value of 'H')
Bytearray (bytearray)
Bytearrays are mutable versions of bytes, allowing you to modify the content after creation.
data = bytearray(b"Hello")
data[0] = 74 # Change 'H' to 'J'
print(data) # Output: bytearray(b'Jello')
Memoryview (memoryview)
Memory views allow you to access the internal data of binary objects without copying them, which is useful for large datasets Practical, not theoretical..
data = b"Hello World"
view = memoryview(data)
print(view[0:5]) # Output:
print(view[0:5].tobytes()) # Output: b'Hello'