Python Data Structures & Comprehensions
This module covers Python’s core data structures (Lists, Tuples, Dictionaries, Sets), queue operations usingdeque, and the powerful comprehension syntax used to create and transform them.
Topics Covered
In this module, you’ll learn:- Lists: CRUD Operations and Sorting
- Tuples: Operations, Indexing, and Slicing
- Dictionaries: CRUD Operations and Sorting
- Sets: CRUD Operations and Sorting
- Queues: Using
collections.deque - Why Comprehensions?
- List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
- Generator Expressions
- Comprehensions vs Loops & Best Practices
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 Download
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
1. Lists: CRUD Operations and Sorting
A List in Python is an ordered, mutable sequence of elements. It is one of the most widely used data structures.Create (C)
You can create a list by enclosing comma-separated values in square brackets[] or by using the list() constructor.
Show Output
Show Output
Read (R) - Indexing & Slicing
Elements in a list are accessed using zero-based indexing, negative indexing (from the end), or slicing (list[start:stop:step]).
Show Output
Show Output
Update (U)
Since lists are mutable, you can modify elements in-place, append new elements, insert at specific positions, or extend with another list.Show Output
Show Output
Delete (D)
You can remove elements from a list using.remove(), .pop(), .clear(), or the del statement.
Show Output
Show Output
Sorting
Python lists can be sorted in-place using.sort() or out-of-place using the global sorted() function.
Show Output
Show Output
Exercise 1
Write a program to create a list of numbers, append10, insert 5 at index 0, and then sort it in-place in descending order.
Solution
Solution
Exercise 2
Given a listarr = ["apple", "cherry", "banana"], remove the element "cherry" and print the sorted list.
Solution
Solution
2. Tuples: Operations, Indexing, and Slicing
A Tuple is an ordered, immutable sequence of elements. Once created, a tuple’s elements cannot be modified, added, or removed.Create (C)
Tuples are defined using parentheses() or the tuple() constructor. To define a tuple with a single element, you must include a trailing comma.
Show Output
Show Output
Read (R) - Indexing & Slicing
Tuples support the exact same indexing and slicing syntax as lists (zero-based indexing, negative indexing, and slicing with[start:stop:step]).
Show Output
Show Output
Operations
Although immutable, tuples support common operations such as concatenation, repetition, membership testing, and element counting.Show Output
Show Output
Sorting
Because tuples are immutable, you cannot sort them in-place. You must use thesorted() function, which returns a new sorted list. You can convert this list back to a tuple if needed.
Show Output
Show Output
Exercise 1
Create a tuple containing elements10, 20, 30, 40, 50. Extract the middle three elements using slicing.
Solution
Solution
Exercise 2
Given the tupledata = (5, 2, 9, 1), write a program to sort it in ascending order and print the result as a tuple.
Solution
Solution
3. Dictionaries: CRUD Operations and Sorting
A Dictionary in Python is a mutable, key-value collection. Keys must be unique and immutable.Create (C)
Create dictionaries using curly braces{} containing key-value pairs or the dict() constructor.
Show Output
Show Output
Read (R)
Values are retrieved using key indexing or the safer.get() method.
Show Output
Show Output
Update (U)
You can add new key-value pairs or modify existing ones simply by assigning to a key, or by using.update().
Show Output
Show Output
Delete (D)
Items can be removed usingdel, .pop() (returns value), .popitem() (removes last inserted pair), or .clear().
Show Output
Show Output
Sorting
Dictionaries can be sorted by keys or values using thesorted() function on their items.
Show Output
Show Output
Exercise 1
Create a dictionary representing a book with key-value pairs fortitle, author, and price. Update the price to 499, add a new key year as 2024, and print all keys in the dictionary.
Solution
Solution
Exercise 2
Givend = {"z": 1, "y": 2, "x": 3}, sort the dictionary by keys in ascending order and print the resulting dictionary.
Solution
Solution
4. Sets: CRUD Operations and Sorting
A Set in Python is an unordered collection of unique, immutable elements. Sets do not allow duplicate values.Create (C)
Sets are created using curly braces{} containing elements or the set() constructor. Note that an empty set must be created using set(), as {} creates an empty dictionary.
Show Output
Show Output
Read (R)
Since sets are unordered, they do not support indexing or slicing. You read elements by checking membership (in) or by iterating over the set.
Show Output
Show Output
Update (U)
You can add elements using.add() (for a single element) or .update() (for multiple elements).
Show Output
Show Output
Delete (D)
Remove elements using.remove() (raises KeyError if not found), .discard() (safe, does not raise error), .pop() (removes and returns an arbitrary element), or .clear().
Show Output
Show Output
Sorting
Since sets are inherently unordered, they cannot be sorted in-place. However, you can use thesorted() function, which returns a sorted list of the set’s elements.
Show Output
Show Output
Exercise 1
Create an empty set, add elements10, 20, and 30 to it, remove 20, and verify if 20 is still in the set.
Solution
Solution
Exercise 2
Given a setmy_set = {15, 5, 25, 10}, sort the elements of the set and print the result.
Solution
Solution
5. Queues: Using collections.deque
A queue is a linear data structure that follows the FIFO (First-In, First-Out) principle.
Although you can use a Python list as a queue by calling list.pop(0), this operation is inefficient. Shifting elements at index 0 requires time complexity.
Python’s collections.deque (double-ended queue) is specifically designed to allow fast appends and pops from both ends in time complexity.
Creating and Enqueuing Elements
Importdeque from collections, and use .append() to enqueue items to the right side of the queue.
Show Output
Show Output
Dequeuing Elements
Use.popleft() to remove and return elements from the left side (front of the queue), preserving the FIFO order.
Show Output
Show Output
Add to Front / Remove from Back
Becausedeque is double-ended, you can also perform LIFO operations or add to the front:
appendleft(item): Add an element to the front.pop(): Remove and return an element from the back.
Show Output
Show Output
Exercise 1
Create a queue usingdeque containing ["user1", "user2"]. Enqueue "user3", dequeue the first user in line, and print the remaining queue.
Solution
Solution
Exercise 2
Write a program to demonstrate how to usedeque as a stack (Last-In, First-Out) using .append() and .pop().
Solution
Solution
6. Why Comprehensions?
Suppose we want to create a list containing the squares of numbers from1 to 5. A common approach is to use a for loop.
Show Output
Show Output
Show Output
Show Output
General Syntax
Show Output
Show Output
- expression → Value to be added to the collection.
- item → Current element from the iterable.
- iterable → Any iterable object such as a string, list, tuple, range, or set.
7. List Comprehensions
A list comprehension creates a new list by applying an expression to each element of an iterable.Basic List Comprehension
Show Output
Show Output
Filtering with if
You can filter elements by adding an if clause at the end.
Show Output
Show Output
Using if-else (Transformation)
To transform values differently based on a condition, place the if-else clause before the for loop.
Show Output
Show Output
Nested List Comprehensions (Flattening)
You can nest comprehensions to work with multi-dimensional lists (e.g., flattening a matrix).Show Output
Show Output
Exercise 1
Create a list containing the lengths of each word in the list["Python", "FastAPI", "API"] using a list comprehension.
Solution
Solution
8. Dictionary Comprehensions
A dictionary comprehension provides a concise way to create dictionaries from iterables.Basic Dictionary Comprehension
Show Output
Show Output
Filtering in Dictionary Comprehensions
Show Output
Show Output
Exercise 1
Given the list["a", "b", "c"], create a dictionary where each character is a key, and its ASCII code (ord(char)) is the value.
Solution
Solution
9. Set Comprehensions
A set comprehension creates a set. Since sets store unique values, duplicates are automatically removed.Basic Set Comprehension
Show Output
Show Output
Exercise 1
Extract all unique vowels from the string"Artificial Intelligence" in lowercase using a set comprehension.
Solution
Solution
10. Generator Expressions
A generator expression is similar to a list comprehension, but instead of creating the entire list in memory, it produces values one at a time (lazy evaluation) using iterators.Syntax
Replace square brackets[] with parentheses ().
Show Output
Show Output
11. Comprehensions vs Loops & Best Practices
Best Practices
- Use comprehensions for simple, readable mappings or filter operations.
- Avoid nesting comprehensions more than 2 levels deep to keep code readable.
- Use generator expressions when working with large or infinite datasets.
- If the loop body contains complex conditional logic, prefer a standard
forloop.
Practice
To reinforce what you’ve learned in this section, practice with the interactive follow-along notebook:Follow-Along Practice
Practice lists, tuples, dictionaries, sets operations, deque queues, list/dict/set comprehensions, and generator expressions.💻 VS Code | 🚀 Colab | 📥 Download