Python is a versatile and powerful programming language known for its simplicity and readability. One of the foundational concepts in Python is its data types. Data types define the type of data a variable can hold, such as integers, floating-point numbers, strings, and more. Understanding data types is crucial for writing efficient and error-free code. This comprehensive guide will delve into Python's built-in data types, providing examples and explanations to help you master their usage.
Data types in Python define the kind of value a variable can hold and what operations can be performed on it. Python is a dynamically typed language, which means you don't need to declare the type of a variable explicitly. The interpreter infers the type based on the value assigned.
num = 10 # Integer
pi = 3.14 # Float
name = "Alice" # String
Understanding data types helps in:
Python supports three distinct numeric types:
int
)float
)complex
)int
)Integers are whole numbers without a fractional part. They can be positive, negative, or zero.
positive_int = 42
negative_int = -99
zero = 0
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a // b) # Floor Division: 3
print(a % b) # Modulus: 1
print(a ** b) # Exponentiation: 1000
float
)Floats represent real numbers with decimal points.
positive_float = 3.1416
negative_float = -2.718
scientific_notation = 1.5e2 # Equivalent to 150.0
x = 5.5
y = 2.0
print(x + y) # 7.5
print(x / y) # 2.75
complex
)Complex numbers have a real and an imaginary part, represented as a + bj
, where a
is the real part and b
is the imaginary part.
complex_num = 2 + 3j
print(complex_num.real) # Output: 2.0
print(complex_num.imag) # Output: 3.0
c1 = 1 + 2j
c2 = 3 + 4j
print(c1 + c2) # Output: (4+6j)
print(c1 * c2) # Output: (-5+10j)
Sequence types represent ordered collections of items.
str
)Strings are sequences of Unicode characters enclosed in quotes.
single_quote_str = 'Hello, World!'
double_quote_str = "Python is fun"
triple_quote_str = """This is a
multi-line string."""
greeting = "Hello"
name = "Alice"
# Concatenation
message = greeting + ", " + name + "!"
print(message) # Output: Hello, Alice!
# Repetition
print("Python! " * 3) # Output: Python! Python! Python!
# Slicing
print(name[0]) # Output: A
print(name[1:4]) # Output: lic
list
)Lists are mutable sequences, typically used to store collections of homogeneous items.
fruits = ['apple', 'banana', 'cherry']
# Accessing elements
print(fruits[0]) # Output: apple
# Modifying elements
fruits[1] = 'blueberry'
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
# Adding elements
fruits.append('date')
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date']
# Removing elements
fruits.remove('apple')
print(fruits) # Output: ['blueberry', 'cherry', 'date']
tuple
)Tuples are immutable sequences, often used to store collections of heterogeneous data.
coordinates = (10.0, 20.0)
# Accessing elements
print(coordinates[0]) # Output: 10.0
# Tuples are immutable, so you cannot modify them:
# coordinates[0] = 15.0 # This will raise a TypeError
dict
)Dictionaries are unordered collections of key-value pairs.
student = {
'name': 'John Doe',
'age': 20,
'courses': ['Math', 'Science']
}
# Accessing values
print(student['name']) # Output: John Doe
# Adding a new key-value pair
student['grade'] = 'A'
print(student)
# Updating a value
student['age'] = 21
# Removing a key-value pair
del student['courses']
print(student)
for key, value in student.items():
print(f"{key}: {value}")
Sets are unordered collections of unique elements.
set
)numbers = {1, 2, 3, 4, 5}
# Adding elements
numbers.add(6)
# Removing elements
numbers.discard(3)
# Set operations
evens = {2, 4, 6, 8}
print(numbers.union(evens)) # Union
print(numbers.intersection(evens)) # Intersection
print(numbers.difference(evens)) # Difference
frozenset
)Frozen sets are immutable sets.
immutable_set = frozenset([1, 2, 3, 4, 5])
bool
)Booleans represent one of two values: True
or False
.
is_active = True
is_deleted = False
print(is_active and is_deleted) # Output: False
print(is_active or is_deleted) # Output: True
print(not is_active) # Output: False
bytes
)Immutable sequences of bytes.
byte_data = b"Hello, Bytes!"
bytearray
)Mutable sequences of bytes.
byte_array = bytearray(b"Hello, Bytearray!")
byte_array[0] = 104 # ASCII for 'h'
print(byte_array) # Output: bytearray(b'hello, Bytearray!')
memoryview
)Allows viewing the memory of other binary objects without copying.
byte_data = b"abcdef"
mem_view = memoryview(byte_data)
print(mem_view[0]) # Output: 97 (ASCII for 'a')
NoneType
)Represents the absence of a value.
result = None
if result is None:
print("No result available.")
Convert between data types using built-in functions.
# String to Integer
num_str = "100"
num_int = int(num_str)
# Integer to String
age = 30
age_str = str(age)
# Float to Integer
pi = 3.14
pi_int = int(pi) # Output: 3
# List to Tuple
fruits_list = ['apple', 'banana']
fruits_tuple = tuple(fruits_list)
# Tuple to List
coordinates = (10.0, 20.0)
coordinates_list = list(coordinates)
list
, dict
, set
, bytearray
int
, float
, str
, tuple
, frozenset
, bytes
# Mutable
colors = ['red', 'green']
colors.append('blue') # Modifies the list
# Immutable
name = "Alice"
# name[0] = 'a' # Raises TypeError
Problem:
Manage user profiles with details like name, age, and hobbies.
# List of user profiles
users = [
{
'name': 'Alice',
'age': 30,
'hobbies': ['reading', 'hiking']
},
{
'name': 'Bob',
'age': 25,
'hobbies': ['gaming', 'coding']
}
]
# Accessing user information
for user in users:
print(f"Name: {user['name']}")
print(f"Age: {user['age']}")
print(f"Hobbies: {', '.join(user['hobbies'])}")
print("-" * 20)
Name: Alice
Age: 30
Hobbies: reading, hiking
--------------------
Name: Bob
Age: 25
Hobbies: gaming, coding
--------------------
Problem:
Calculate the average score from a list of student grades.
# List of tuples containing student names and their grades
grades = [
('Alice', 85),
('Bob', 92),
('Charlie', 78),
('Diana', 90)
]
# Calculate the average grade
total = 0
for student, grade in grades:
total += grade
average = total / len(grades)
print(f"The average grade is: {average:.2f}")
The average grade is: 86.25
Data types are the backbone of Python programming, defining how data is stored and manipulated. This guide covered Python's built-in data types, including numbers, sequences, mappings, sets, booleans, and binary types. Understanding these data types enables you to choose the right structures for your data, write more efficient code, and avoid common pitfalls.
Remember to consider mutability when working with data structures, and use type conversion functions to manipulate data as needed. By mastering Python's data types, you lay a strong foundation for advanced programming concepts and real-world application development.