Structuring Data In Python¶
Overview¶
Structuring data in Python involves organizing and storing data in ways that make it efficient to access, modify, and analyze. Python provides several built-in data structures and tools to support this.
Core Data Structures¶
Lists¶
Lists are ordered, mutable collections.
Defined using square brackets
[]Can store mixed data types
Support indexing and slicing
Example:
numbers = [1, 2, 3, 4]
numbers.append(5)
Tuples¶
Tuples are ordered, immutable collections.
Defined using parentheses
()Cannot be changed after creation
Useful for fixed data
Example:
point = (10, 20)
Dictionaries¶
Dictionaries store key-value pairs.
Defined using curly braces
{}Keys must be unique and immutable
Values can be any type
Example:
user = {"name": "Alice", "age": 25}
print(user["name"])
Sets¶
Sets are unordered collections of unique elements.
Defined using
{}orset()Automatically remove duplicates
Support set operations
Example:
unique_numbers = {1, 2, 2, 3}
Custom Data Structures¶
Classes¶
Classes allow you to create custom data structures.
Combine data (attributes) and behavior (methods)
Support object-oriented design
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 25)
Data Classes¶
Data classes simplify class creation for storing data.
Introduced in Python 3.7
Automatically generate
__init__,__repr__, etc.
Example:
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
Nested Structures¶
Data structures can be combined to represent complex data.
Example:
students = [
{"name": "Alice", "grades": [90, 85, 88]},
{"name": "Bob", "grades": [78, 82, 80]}
]
Benefits: - Represent real-world relationships - Enable hierarchical data organization
Choosing the Right Structure¶
Consider the following:
Use lists for ordered, changeable collections
Use tuples for fixed data
Use dictionaries for fast key-based lookup
Use sets for uniqueness and membership testing
Summary¶
Effective data structuring in Python helps:
Improve performance
Simplify code
Enhance readability and maintainability
Common tools include lists, tuples, dictionaries, sets, and classes.