Python_Data_Structures
Python_Data_Structures
• Features
• - Keys are unique and immutable.
• - Values can be any data type.
• Example
• student = {"name": "Alice", "age": 21, "grade": "A"}
• Common Operations
• - Access: student["name"]
• - Add: student["major"] = "Math"
• - Delete: del student["grade"]
Tuple
• Definition
• - An ordered, immutable collection of items.
• - Syntax: (item1, item2, ...)
• Features
• - Immutable: Cannot modify after creation.
• - Supports indexing and slicing.
• Example
• coordinates = (10, 20, 30)
• Common Operations
• - Access: coordinates[0]
• - Length: len(coordinates)
• - Count: coordinates.count(20)
Set
• Definition
• - An unordered collection of unique items.
• - Syntax: {item1, item2, ...}
• Features
• - No duplicate elements.
• - Supports mathematical set operations (union, intersection).
• Example
• fruits = {"apple", "banana", "cherry"}
• Common Operations
• - Add: fruits.add("orange")
• - Remove: fruits.remove("banana")
• - Union: fruits.union({"grape"})
Key Differences
• Dictionary vs Tuple vs Set
• | Feature | Dictionary | Tuple | Set |
• |----------------|-----------------------|---------------|-------------|
• | Order | Unordered | Ordered | Unordered |
• | Mutability | Mutable keys/values | Immutable | Mutable |
• | Duplicates | Keys must be unique | Allows | No |
Use Cases
• Dictionary
• - Storing structured data (e.g., student records).
• Tuple
• - Fixed data (e.g., geographical coordinates).
• Set
• - Membership tests, removing duplicates, and set
operations.
Code Comparison
• Dictionary Example
• employee = {"id": 1, "name": "John"}
• print(employee["name"])
• Tuple Example
• colors = ("red", "green", "blue")
• print(colors[1])
• Set Example
• numbers = {1, 2, 3, 4}
• numbers.add(5)
• print(numbers)
Summary
• Dictionary
• - Key-value pairs, mutable.
• Tuple
• - Immutable, ordered.
• Set
• - Unique, unordered elements.