Lists & Dictionaries
advancedPart of Python in Practice
Theory
Lists are ordered, mutable sequences of elements enclosed in square brackets []. They can contain elements of any type, including mixed types.
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]Access elements by index (zero-based): fruits[0] is "apple". Negative indices count from the end: fruits[-1] is "cherry". Slicing extracts portions: fruits[1:3] returns ["banana", "cherry"].
List methods:
- Adding elements:
append(),extend(),insert() - Removing elements:
remove()(by value),pop()(by index),clear() - Reordering:
sort(),reverse() - Searching:
index(),count()
List comprehensions offer a concise way to create lists:
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]Tuples are ordered, immutable sequences enclosed in parentheses (). Once created, they cannot be modified. Use tuples for data that should not change (e.g., coordinates, RGB values).
point = (3, 4)
rgb = (255, 128, 0)
x, y = point # tuple unpackingDictionaries store key-value pairs enclosed in curly braces {}. Keys must be immutable (strings, numbers, tuples). Values can be any type.
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"]) # AliceDictionary methods:
get(key, default)— safe access with fallbackkeys()— all keysvalues()— all valuesitems()— key-value pairs as tuplesupdate(dict2)— merge another dictionarypop(key)— remove and return value
Dictionary comprehensions create dictionaries concisely:
squares = {x: x**2 for x in range(5)}Sets are unordered collections of unique elements. Created with set() or curly braces {} (but {} creates a dict if empty).
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1,2,3,4,5,6}
print(a & b) # intersection: {3,4}
print(a - b) # difference: {1,2}Use sets when you need uniqueness or set operations.
Practical Examples
Exercises
Shopping List Organizer
Create a shopping list: ['milk', 'eggs', 'bread', 'butter', 'apples']. Use list methods to: add 'cheese' to the end, insert 'bananas' at position 2, remove 'eggs', sort the list alphabetically, and print the final list.
Starter Code:
shopping = ['milk', 'eggs', 'bread', 'butter', 'apples']\n# Your code hereExpected Output:
['apples', 'bananas', 'bread', 'butter', 'cheese']Word Frequency Counter
Given a sentence: 'the quick brown fox jumps over the lazy dog the fox', write code that: 1) Splits the sentence into words, 2) Creates a dictionary counting how many times each word appears, 3) Prints the words that appear more than once. Use a dictionary comprehension.
Starter Code:
sentence = 'the quick brown fox jumps over the lazy dog the fox'\n# Your code hereExpected Output:
Word frequencies: {'the': 3, 'quick': 1, 'brown': 1, 'fox': 2, ...}\nDuplicate words: the, foxSet Operations on Tags
Two blog posts have these tags: post1_tags = {'python', 'tutorial', 'beginner', 'coding'} and post2_tags = {'python', 'advanced', 'coding', 'web'}. Find: 1) Tags common to both posts, 2) All unique tags across both posts, 3) Tags unique to post1, 4) Tags unique to post2. Use set operations.
Starter Code:
post1_tags = {'python', 'tutorial', 'beginner', 'coding'}\npost2_tags = {'python', 'advanced', 'coding', 'web'}\n# Your set operations hereExpected Output:
Common: {'python', 'coding'}\nAll: {'python', 'tutorial', 'beginner', 'coding', 'advanced', 'web'}\nPost1 only: {'tutorial', 'beginner'}\nPost2 only: {'advanced', 'web'}Mini Quiz
Mini Quiz
Mini Project
Mini Project: Contact Book Manager
Build a contact book program that stores names, phone numbers, and email addresses using dictionaries and lists.
Requirements:
Bonus Challenge
Add the ability to update a contact's phone number and merge two contact books.