Skip to main content

Python Data Structures & Comprehensions

This module covers Python’s core data structures (Lists, Tuples, Dictionaries, Sets), queue operations using deque, and the powerful comprehension syntax used to create and transform them.

Topics Covered

In this module, you’ll learn:
  1. Lists: CRUD Operations and Sorting
  2. Tuples: Operations, Indexing, and Slicing
  3. Dictionaries: CRUD Operations and Sorting
  4. Sets: CRUD Operations and Sorting
  5. Queues: Using collections.deque
  6. Why Comprehensions?
  7. List Comprehensions
  8. Dictionary Comprehensions
  9. Set Comprehensions
  10. Generator Expressions
  11. 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.
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]).
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.
Output ?

Delete (D)

You can remove elements from a list using .remove(), .pop(), .clear(), or the del statement.
Output ?

Sorting

Python lists can be sorted in-place using .sort() or out-of-place using the global sorted() function.
Output ?

Exercise 1

Write a program to create a list of numbers, append 10, insert 5 at index 0, and then sort it in-place in descending order.

Exercise 2

Given a list arr = ["apple", "cherry", "banana"], remove the element "cherry" and print the sorted list.

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.
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]).
Output ?

Operations

Although immutable, tuples support common operations such as concatenation, repetition, membership testing, and element counting.
Output ?

Sorting

Because tuples are immutable, you cannot sort them in-place. You must use the sorted() function, which returns a new sorted list. You can convert this list back to a tuple if needed.
Output ?

Exercise 1

Create a tuple containing elements 10, 20, 30, 40, 50. Extract the middle three elements using slicing.

Exercise 2

Given the tuple data = (5, 2, 9, 1), write a program to sort it in ascending order and print the result as a tuple.

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.
Output ?

Read (R)

Values are retrieved using key indexing or the safer .get() method.
Output ?

Update (U)

You can add new key-value pairs or modify existing ones simply by assigning to a key, or by using .update().
Output ?

Delete (D)

Items can be removed using del, .pop() (returns value), .popitem() (removes last inserted pair), or .clear().
Output ?

Sorting

Dictionaries can be sorted by keys or values using the sorted() function on their items.
Output ?

Exercise 1

Create a dictionary representing a book with key-value pairs for title, author, and price. Update the price to 499, add a new key year as 2024, and print all keys in the dictionary.

Exercise 2

Given d = {"z": 1, "y": 2, "x": 3}, sort the dictionary by keys in ascending order and print the resulting dictionary.

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.
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.
Output ?

Update (U)

You can add elements using .add() (for a single element) or .update() (for multiple elements).
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().
Output ?

Sorting

Since sets are inherently unordered, they cannot be sorted in-place. However, you can use the sorted() function, which returns a sorted list of the set’s elements.
Output ?

Exercise 1

Create an empty set, add elements 10, 20, and 30 to it, remove 20, and verify if 20 is still in the set.

Exercise 2

Given a set my_set = {15, 5, 25, 10}, sort the elements of the set and print the result.

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 O(n)O(n) time complexity. Python’s collections.deque (double-ended queue) is specifically designed to allow fast appends and pops from both ends in O(1)O(1) time complexity.

Creating and Enqueuing Elements

Import deque from collections, and use .append() to enqueue items to the right side of the queue.
Output ?

Dequeuing Elements

Use .popleft() to remove and return elements from the left side (front of the queue), preserving the FIFO order.
Output ?

Add to Front / Remove from Back

Because deque 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.
Output ?

Exercise 1

Create a queue using deque containing ["user1", "user2"]. Enqueue "user3", dequeue the first user in line, and print the remaining queue.

Exercise 2

Write a program to demonstrate how to use deque as a stack (Last-In, First-Out) using .append() and .pop().

6. Why Comprehensions?

Suppose we want to create a list containing the squares of numbers from 1 to 5. A common approach is to use a for loop.
Python provides comprehensions to perform the same task in a cleaner, single-line expression:
Output ?

General Syntax

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

Output ?

Filtering with if

You can filter elements by adding an if clause at the end.
Output ?

Using if-else (Transformation)

To transform values differently based on a condition, place the if-else clause before the for loop.
Output ?

Nested List Comprehensions (Flattening)

You can nest comprehensions to work with multi-dimensional lists (e.g., flattening a matrix).
Output ?

Exercise 1

Create a list containing the lengths of each word in the list ["Python", "FastAPI", "API"] using a list comprehension.

8. Dictionary Comprehensions

A dictionary comprehension provides a concise way to create dictionaries from iterables.

Basic Dictionary Comprehension

Output ?

Filtering in Dictionary Comprehensions

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.

9. Set Comprehensions

A set comprehension creates a set. Since sets store unique values, duplicates are automatically removed.

Basic Set Comprehension

Output ?

Exercise 1

Extract all unique vowels from the string "Artificial Intelligence" in lowercase using a set comprehension.

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 ().
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 for loop.

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

Summary

In this module, you learned how to manipulate Python’s core data structures (Lists, Tuples, Dictionaries, Sets), use double-ended queues, and write clean, memory-efficient comprehensions.