๐ Understanding Python Data Structures: Lists, Sets, and Dictionaries
PYTHON
5/3/20254 min read


Python is a powerful and beginner-friendly language, and one of its strengths lies in its built-in data structures. In this post, weโll explore three fundamental ones: lists, sets, and dictionaries. Each serves a specific purpose and can make your code cleaner and more efficient.
๐ 1. Lists โ Ordered Collections
A list is an ordered collection of items that can be changed (mutable). You can store anything in a list: numbers, strings, or even other lists!
โ Creating a List
fruits = ['apple', 'banana', 'cherry']
๐ง Common Operations
fruits.append('orange') # Add item
fruits.remove('banana') # Remove item
print(fruits[1]) # Access by index
print(len(fruits)) # Length of list
๐ Looping Through a List
for fruit in fruits:
print(fruit)
๐ง Use Case
Use lists when you need an ordered collection of items that can contain duplicates and allow indexing.
List Example 1:
fruits = ['apple', 'banana', 'cherry']
print("Initial list")
print(fruits)
fruits.append('orange') # Add item
fruits.remove('banana') # Remove item
print("modified list")
print(fruits)
print("Value at index 1:")
print(fruits[1]) # Access by index
print("number of fruits in the list:")
print(len(fruits)) # Length of list
OUTPUT:
Initial list
['apple', 'banana', 'cherry']
modified list
['apple', 'cherry', 'orange']
Value at index 1:
cherry
number of fruits in the list:
3
List Example 2 โ Filtering Even Numbers from a List
numbers = [1, 4, 7, 10, 13, 16, 19, 22]
even_numbers = [num for num in numbers if num % 2 == 0]
print("Even numbers:", even_numbers)
OUTPUT:
Even numbers: [4, 10, 16, 22]
List Example 3 โ To-Do List Manager
todo_list = []
# Add tasks
todo_list.append("Buy groceries")
todo_list.append("Call John")
todo_list.append("Read a book")
# Show tasks
print("To-do list:")
for i, task in enumerate(todo_list, start=1):
print(f"{i}. {task}")
# Remove a completed task
todo_list.remove("Call John")
print("\nUpdated to-do list:", todo_list)
OUTPUT:
To-do list:
1. Buy groceries
2. Call John
3. Read a book
Updated to-do list: ['Buy groceries', 'Read a book']
๐ฃ 2. Sets โ Unordered Unique Collections
A set is an unordered collection of unique elements. Itโs great for membership tests and removing duplicates.
โ Creating a Set
colors = {'red', 'blue', 'green'}
๐ง Common Operations
colors.add('yellow') # Add item
colors.discard('blue') # Remove item
print('red' in colors) # Membership test
๐ Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
print(a.difference(b)) # {1, 2}
๐ง Use Case
Use sets when you want to store unique items and perform operations like unions or intersections.
Set Example 1 โ Removing Duplicate Emails
emails = [
"alice@example.com", "bob@example.com", "alice@example.com", "carol@example.com"
]
unique_emails = set(emails)
print("Unique emails:", unique_emails)
OUTPUT:
Unique emails: {'carol@example.com', 'alice@example.com', 'bob@example.com'}
Set Example 2 โ Finding Common Tags Between Two Blog Posts
post1_tags = {"python", "data", "tutorial", "beginner"}
post2_tags = {"python", "flask", "web", "tutorial"}
common_tags = post1_tags.intersection(post2_tags)
print("Common tags:", common_tags)
OUTPUT:
Common tags: {'tutorial', 'python'}
๐ 3. Dictionaries โ Key-Value Pairs
A dictionary (or dict) stores data in key-value pairs. Think of it like a real dictionary where a word (key) maps to a definition (value).
โ Creating a Dictionary
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
๐ง Common Operations
print(person['name']) # Access value
person['age'] = 31 # Update value
person['email'] = 'alice@example.com' # Add new key-value pair
del person['city'] # Delete key-value pair
๐ Looping Through a Dictionary
for key, value in person.items():
print(f"{key}: {value}")
๐ง Use Case
Use dictionaries when you need to associate keys with values for fast lookups or to represent structured data.
Dictionary Example 1 โ Counting Word Frequency
text = "python is great and python is easy to learn"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print("Word frequency:", word_count)
OUTPUT:
Word frequency: {'python': 2, 'is': 2, 'great': 1, 'and': 1, 'easy': 1, 'to': 1, 'learn': 1}
Dictionary Example 2 โ Student Grades Lookup
grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
# Look up a grade
print("Alice's grade:", grades["Alice"])
# Add a new student
grades["David"] = 88
# Update a grade
grades["Charlie"] = 82
# List all grades
print("\nAll student grades:")
for student, grade in grades.items():
print(f"{student}: {grade}")
OUTPUT:
Alice's grade: 85
All student grades:
Alice: 85
Bob: 92
Charlie: 82
David: 88
More Examples:
Event RSVP Manager
Track RSVPs for an event: invited guests, who responded, and their preferences.
invited = ["Alice", "Bob", "Charlie", "David"]
responded = {"Alice", "David"}
preferences = {
"Alice": "Vegetarian",
"David": "Non-Vegetarian"
}
# Who hasn't responded yet?
pending = set(invited) - responded
print("Pending RSVPs:", pending)
# Show preferences
print("\nMeal preferences of responded guests:")
for guest in responded:
print(f"{guest}: {preferences.get(guest, 'No preference given')}")
OUTPUT:
Pending RSVPs: {'Bob', 'Charlie'}
Meal preferences of responded guests:
Alice: Vegetarian
David: Non-Vegetarian
Product Inventory Tracker
inventory = {
"apple": 50,
"banana": 20,
"orange": 0,
}
# Add new stock
inventory["banana"] += 30
inventory["kiwi"] = 15
# Show out-of-stock items
out_of_stock = [item for item, qty in inventory.items() if qty == 0]
print("Out-of-stock:", out_of_stock)
# Total items in inventory
total_items = sum(inventory.values())
print("Total items in inventory:", total_items)
OUTPUT:
Out-of-stock: ['orange']
Total items in inventory: 115
Shopping Cart Total Calculator
cart = [
{"item": "apple", "price": 1.2, "quantity": 4},
{"item": "banana", "price": 0.5, "quantity": 6},
{"item": "orange", "price": 0.8, "quantity": 3},
]
total = 0
for product in cart:
item_total = product["price"] * product["quantity"]
total += item_total
print(f"{product['item'].title()} - ${item_total:.2f}")
print(f"\nTotal: ${total:.2f}")
OUTPUT:
Apple - $4.80
Banana - $3.00
Orange - $2.40
Total: $10.20
Who Brought What to the Potluck?
potluck = {
"Alice": {"salad", "juice"},
"Bob": {"bread", "juice"},
"Charlie": {"cake", "salad"},
}
# Who brought salad?
people_with_salad = [name for name, items in potluck.items() if "salad" in items]
print("People who brought salad:", people_with_salad)
# All unique items brought
all_items = set()
for items in potluck.values():
all_items.update(items)
print("Total unique dishes:", all_items)
OUTPUT:
People who brought salad: ['Alice', 'Charlie']
Total unique dishes: {'cake', 'bread', 'juice', 'salad'}
Grouping Students by Grade
students = [
{"name": "Alice", "grade": "A"},
{"name": "Bob", "grade": "B"},
{"name": "Charlie", "grade": "A"},
{"name": "David", "grade": "C"},
]
grouped = {}
for student in students:
grade = student["grade"]
grouped.setdefault(grade, []).append(student["name"])
print("Students grouped by grade:")
for grade, names in grouped.items():
print(f"{grade}: {', '.join(names)}")
OUTPUT:
Students grouped by grade:
A: Alice, Charlie
B: Bob
C: David
Key Takeaways
โ Lists โ Ordered, Mutable Sequences
Maintain the order of items.
Allow duplicates and indexing.
Useful for task management, ordered data, or bulk operations like filtering and transformation.
List comprehensions are powerful for creating and filtering lists in one line.
Example use cases:
To-do lists
Shopping carts
Storing results of computations
โ Sets โ Unordered, Unique Collections
Automatically remove duplicates.
Great for fast membership testing, and performing set operations: union, intersection, difference.
Cannot be indexed and donโt allow duplicates.
Example use cases:
De-duplicating email lists
Tag comparison
Fast lookups in large datasets
โ Dictionaries โ Key-Value Stores
Provide fast access to data by key.
Keys must be unique and immutable (strings, numbers, tuples).
Excellent for organizing structured data, counting, and grouping.
Example use cases:
User profiles (name, age, email)
Word counters
Grouping data by category (e.g. grades, departments)
๐ Combined Usage โ Real Power in Practice
Real-world tasks often combine these structures:
List of dictionaries (e.g. products in a cart)
Dictionary with sets or lists as values (e.g. grouped data, relationships)
This makes them highly flexible and essential for data analysis, web apps, APIs, and automation scripts.
๐จ Pro Tips:
Use sets when you care about membership or uniqueness.
Use dictionaries when you need to map one thing to another.
Use lists when order matters or youโre working with sequences of data.


Kishore Babu Valluri
Senior Data Scientist | Freelance Consultant | AI/ML & GenAI Expert
With deep expertise in machine learning, artificial intelligence, and Generative AI, I work as a Senior Data Scientist, freelance consultant, and AI agent developer. I help businesses unlock value through intelligent automation, predictive modeling, and cutting-edge AI solutions.