1. Lists: Your Swiss Army Knife
Lists are like to-do lists. You can put different things in them and change them anytime. For instance:
my_list = [1, 2, 3, 'apple', 'banana'] my_list.append(4) # You added 4 to the list
2. Dictionaries: Your Treasure Map
Dictionaries are like real-life dictionaries. They have words (keys) and meanings (values). Imagine a character list:
character_dict = {'hero': 'Harry', 'villain': 'Voldemort', 'sidekick': 'Ron'} print(character_dict['hero']) # This gives you 'Harry'
3. Sets: Keep Things Unique
Sets are like unique collections. They don’t allow duplicates. For instance:
my_set = {1, 2, 2, 3, 3} print(my_set) # This prints {1, 2, 3}
4. Tuples: Immutable Artifacts
Tuples are like unchangeable lists. Once you make them, you can’t change them. For example:
coordinates = (3, 4) # You can't do this: coordinates[0] = 5
5. Stacks and Queues: The Heroes and Sidekicks
Stacks are like stacking books, and queues are like waiting in line. Stacks use LIFO, and queues use FIFO. For instance, let’s use a list for a simple stack:
my_stack = []
my_stack.append('hero') # This adds 'hero' on top
my_stack.append('sidekick') # This adds 'sidekick' on top
print(my_stack.pop()) # This gives 'sidekick'
6. Linked Lists: The Intricate Plot
Linked lists are like a chain of connected events. Each event points to the next. Here’s a simplified example:
class Node:
def __init__(self, data):
self.data = data
self.next = None
node1 = Node('start')
node2 = Node('middle')
node1.next = node2
7. Trees: The World-Building
Trees are like family trees. You have a root (ancestors) and branches (descendants). For instance:
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
root = TreeNode('Grandparent')
child1 = TreeNode('Parent')
child2 = TreeNode('Aunt')
root.children.append(child1)
root.children.append(child2)
8. Graphs: The Interconnected Characters
Graphs are like social networks, showing how people (nodes) are connected (edges). A simple example:
graph = {'Alice': ['Bob', 'Carol'], 'Bob': ['Alice', 'David']}
# Alice is friends with Bob and Carol, Bob is friends with Alice and David
In conclusion, Python data structures are like different tools for various tasks. Whether you’re making lists of characters, building a treasure map of items, or crafting intricate plots, these structures help you organize and manage data effectively in your programs and storytelling adventures.
Thanks for reading and happy learning! billy-at-python.sg