5 Data Structures Explained
Key Concepts
Data structures in Python are essential for organizing and storing data efficiently. The key concepts include:
- Lists
- Tuples
- Sets
- Dictionaries
- Strings
1. Lists
Lists are ordered collections of items that can be of different data types. They are mutable, meaning you can change their content after creation.
Example:
fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
Analogy: Think of a list as a shopping list where you can add, remove, or modify items.
2. Tuples
Tuples are similar to lists but are immutable, meaning their content cannot be changed after creation. They are useful for storing data that should not be altered.
Example:
coordinates = (3, 5) print(coordinates[0]) # Output: 3
Analogy: Think of a tuple as a fixed set of coordinates on a map that cannot be changed.
3. Sets
Sets are unordered collections of unique items. They do not allow duplicate values and are useful for performing mathematical set operations like union and intersection.
Example:
unique_numbers = {1, 2, 3, 4, 5} unique_numbers.add(3) print(unique_numbers) # Output: {1, 2, 3, 4, 5}
Analogy: Think of a set as a collection of unique marbles where adding the same marble twice has no effect.
4. Dictionaries
Dictionaries are unordered collections of key-value pairs. They are mutable and allow fast lookups based on the key.
Example:
student_scores = {"Alice": 90, "Bob": 85, "Charlie": 92} student_scores["Alice"] = 95 print(student_scores) # Output: {'Alice': 95, 'Bob': 85, 'Charlie': 92}
Analogy: Think of a dictionary as a phone book where each name (key) has a corresponding phone number (value).
5. Strings
Strings are sequences of characters. They are immutable and can be indexed and sliced like lists.
Example:
greeting = "Hello, World!" print(greeting[0:5]) # Output: Hello
Analogy: Think of a string as a sequence of letters in a word where each letter has a specific position.
Putting It All Together
By understanding and using these data structures effectively, you can create more efficient and organized programs in Python. Each data structure has its unique properties and use cases, making them essential tools in your programming toolkit.
Example:
data = { "fruits": ["apple", "banana", "cherry"], "coordinates": (3, 5), "unique_numbers": {1, 2, 3, 4, 5}, "student_scores": {"Alice": 90, "Bob": 85, "Charlie": 92}, "greeting": "Hello, World!" } print(data["fruits"][1]) # Output: banana print(data["coordinates"][0]) # Output: 3 print(data["unique_numbers"]) # Output: {1, 2, 3, 4, 5} print(data["student_scores"]["Alice"]) # Output: 90 print(data["greeting"][0:5]) # Output: Hello