8. Core Data Structures
Organizing data like a pro
A list is an ordered collection of items. In Python, lists can hold any mix of types — though in practice you'll usually store items of the same type. Lists are one of the most commonly used data structures in all of programming.
# Creating lists numbers = [1, 2, 3, 4, 5] fruits = ['apple', 'mango', 'banana'] mixed = [42, 'hello', True, 3.14] # Accessing items (index starts at 0) print(fruits[0]) # apple print(fruits[-1]) # banana (last item) # Modifying lists fruits.append('orange') # Add to end fruits.insert(1, 'grape') # Add at position 1 fruits.remove('mango') # Remove by value popped = fruits.pop() # Remove and return last item # Slicing print(numbers[1:4]) # [2, 3, 4] — index 1 to 3 print(numbers[:3]) # [1, 2, 3] — first 3 print(numbers[2:]) # [3, 4, 5] — from index 2 # Useful operations print(len(fruits)) # Length print('apple' in fruits) # True — membership check fruits.sort() # Sort in place
Strings & Manipulation
Strings behave a lot like lists — they're ordered sequences of characters. You can slice them, loop through them, and use a rich set of built-in methods:
text = ' Hello, World! ' # Common string methods print(text.strip()) # 'Hello, World!' — remove whitespace print(text.lower()) # ' hello, world! ' print(text.upper()) # ' HELLO, WORLD! ' print(text.replace('World', 'Python')) # replace substring print(text.split(',')) # [' Hello', ' World! '] print(len(text)) # Length including spaces print(text.strip().startswith('Hello')) # True # f-strings (the modern way to format strings) name = 'Ama' age = 22 print(f'My name is {name} and I am {age} years old.')
Objects / Dictionaries
A dictionary stores data as key-value pairs. Instead of accessing items by index number, you access them by a meaningful key — like a real dictionary where you look up a word to get its definition.
# Creating a dictionary user = { 'name': 'Kofi Boateng', 'age': 28, 'email': 'kofi@example.com', 'is_premium': True } # Accessing values print(user['name']) # Kofi Boateng print(user.get('age')) # 28 (safe — won't crash if key missing) # Modifying user['age'] = 29 # Update user['city'] = 'Accra' # Add new key del user['is_premium'] # Delete # Looping through a dictionary for key, value in user.items(): print(f'{key}: {value}')
Introduction to Stacks
A stack is a Last-In-First-Out (LIFO) structure — like a stack of plates. The last plate you put on is the first one you take off. In Python, you implement a stack with a list using append() and pop():
# Stack using a list stack = [] stack.append('page1') # Push stack.append('page2') stack.append('page3') print(stack.pop()) # page3 — last in, first out print(stack.pop()) # page2 print(stack) # ['page1'] # Real use case: browser back button!
Introduction to Queues
A queue is First-In-First-Out (FIFO) — like a line at a bank. The first person who arrives is the first person served. Python has a built-in deque (double-ended queue) for this:
from collections import deque queue = deque() queue.append('Task 1') # Enqueue queue.append('Task 2') queue.append('Task 3') print(queue.popleft()) # Task 1 — first in, first out print(queue.popleft()) # Task 2 # Real use: print jobs, message processing, task scheduling
Choosing the Right Data Structure
The choice of data structure dramatically affects how clean and efficient your code is:
- Use a list when you need an ordered collection you can add to and loop through.
- Use a dictionary when you need to look up values by name/key.
- Use a set when you need unique items and fast membership testing.
- Use a stack when order matters and you need last-in-first-out access.
- Use a queue when you need first-in-first-out processing (tasks, messages).
Knowledge Check
Ready to test your understanding of 8. Core Data Structures?