Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Collection Manipulation Fundamentals

Recommended resources

Hello! In our last lesson, we learned to control the flow of our programs using if/else statements and loops. You saw how for loops allow us to iterate over sequences, performing an action for each item. Now, it's time to master those sequences themselves.

This lesson dives into Python's four fundamental collection data types: lists, tuples, sets, and dictionaries. Understanding how to create, manipulate, and choose between these structures is a cornerstone of effective programming. For a backend engineer, this skill is non-negotiable—it's how you'll manage everything from incoming API request data to database records and user permissions. By the end of this lesson, you'll be able to confidently select and use the right collection for the right job.

1. An Overview of Python's Collections

Python provides four powerful built-in collection types. While they all store multiple items, they differ in key properties like order, mutability (changeability), and whether they allow duplicates. Choosing the correct one can significantly impact your code's performance and readability.

The following table provides a high-level comparison, which we will explore in detail throughout this lesson.

This table summarizes the core characteristics, use cases, and performance attributes of Lists, Tuples, Sets, and Dictionaries.

The two most important distinctions to grasp are:

  • Mutability: Can the collection be changed after it's created? Lists, sets, and dictionaries are mutable. Tuples are immutable.
  • Ordering: Do the items maintain a reliable order? Lists and tuples are ordered. Sets are unordered. Dictionaries maintain insertion order in modern Python (3.7+).

Let's begin our deep dive with a comprehensive video that covers the essentials of these data types.

Python: Data Structures - Lists, Tuples, Sets & Dictionaries tutorial

This video provides a concise introduction to all four data structures, highlighting their core differences.

Watch the overview from the beginning until the end of the introduction. Pay close attention to the summary of when you might use each type.


2. Lists: The Dynamic Workhorse

Lists are ordered, mutable collections of items, and they are arguably the most common data structure you'll use in Python. You can add, remove, and change elements, making them incredibly flexible.

In the previous lesson, you saw how to iterate over a list. Now, let's learn how to manipulate it. The following video from Corey Schafer is an excellent, detailed guide to working with lists.

Python Tutorial for Beginners 4: Lists, Tuples, and Sets

This video provides a thorough walkthrough of list operations, from basic access to advanced manipulation.

Please watch the following segments: Basics & Slicing: This section reviews list creation, accessing elements with indices (courses[0]), and slicing (courses[0:2]). Modifying Lists: Watch from this point to learn key methods like .append(), .insert(), .extend(), .remove(), and .pop(). Sorting: The segment from here explains the difference between .sort() (in-place) and the sorted() function (returns a new list). Finding & Iterating: Watch from this section to see how to find items with .index(), check for presence with the in keyword, and loop using enumerate() to get both index and value. String Conversion: Finally, watch from this part to learn the very useful .join() and .split() methods for converting between lists and strings.

For a detailed written reference on lists, including examples of slicing and modification, you can study the following text.

Python Data Structures: Lists, Dictionaries, Sets, Tuples

This section from the Dataquest article offers a solid written explanation of lists.

Read the section titled "Lists". It covers what makes a list dynamic and mutable, and provides clear code examples for creation, indexing, slicing, and modification.


3. Tuples: The Immutable Sibling

Tuples are almost identical to lists—they are ordered collections—but with one critical difference: they are immutable. Once you create a tuple, you cannot change its contents. This might seem like a limitation, but it's a powerful feature for data integrity. You use tuples when you want to ensure that a collection of values, like coordinates or configuration settings, doesn't change accidentally.

Python Tutorial for Beginners 4: Lists, Tuples, and Sets

This part of the Corey Schafer video explains the concept of immutability and why you would choose a tuple over a list.

Watch the section on tuples from the beginning. Notice the TypeError when an attempt is made to change a tuple's element.

A key advantage of their immutability is that tuples can be used as keys in a dictionary, whereas lists cannot. This is because dictionary keys must be "hashable," a property that requires them to be unchangeable.


4. Sets: For Uniqueness and Mathematical Operations

Sets are unordered collections of unique elements. Their two primary strengths are:

  1. Enforcing uniqueness: Sets automatically discard duplicate values. This makes them perfect for quickly de-duplicating a list.
  2. Fast membership testing: Checking if an item is in a set is significantly faster than checking if it's in a list, especially for large collections.

They also support powerful mathematical operations like union, intersection, and difference.

Python Tutorial for Beginners 4: Lists, Tuples, and Sets

The final segments of the video cover sets, from their basic properties to advanced operations.

Introduction to Sets: Watch from this section to understand how sets handle order and duplicates, and their efficiency in membership testing. Set Operations: The part from here demonstrates .intersection(), .difference(), and .union(). Creating Empty Sets: Watch the quick but important final tip from this point to learn the correct way to create an empty set (set()) versus an empty dictionary ({}).


5. Dictionaries: The Key-Value Store

Dictionaries are Python's implementation of a hash map or associative array. They store data in key-value pairs. This is an extremely common pattern in backend development, used for everything from representing JSON objects from an API to structuring records from a database. In modern Python (3.7+), dictionaries are also ordered, meaning they remember the order in which items were inserted.

Python: Data Structures - Lists, Tuples, Sets & Dictionaries tutorial

This video provides a quick but thorough guide to dictionary operations.

Watch the section on dictionaries starting from this timestamp. It covers creation, adding/changing items, accessing keys and values, and iterating.

The ability to look up a value by its key instantly (O(1) average time complexity) makes dictionaries incredibly fast and efficient for lookups.

Python Data Structures: Lists, Dictionaries, Sets, Tuples

This article section reinforces the concepts shown in the video.

Read the section titled "Dictionaries". Focus on the "pros" and "cons" and the example of nesting a dictionary within another dictionary, a very common structure.


6. Hands-On Practice

Time to apply this knowledge. Create a new Python file, collections_practice.py, and complete the following tasks.

Task 1: Process User Tags

You receive a list of tags from a user profile, but it contains duplicates. Your task is to produce a clean, alphabetized list of unique tags.

user_tags = ['python', 'backend', 'django', 'api', 'python', 'rest', 'api']




# 1. Use a set to get the unique tags.
unique_tags_set = set(user_tags)




# 2. Convert the set back to a list to be able to sort it.
unique_tags_list = list(unique_tags_set)




# 3. Sort the list alphabetically.
unique_tags_list.sort()




# 4. Print the final list.
print(f"Unique, sorted tags: {unique_tags_list}")



# Expected output: Unique, sorted tags: ['api', 'backend', 'django', 'python', 'rest']

Task 2: Group Employees by Department

This is a classic backend data-processing task. You have a list of employee records (as dictionaries). Your goal is to create a new dictionary that groups employee names by their department.

employees = [
    {'name': 'Alice', 'dept': 'Engineering'},
    {'name': 'Bob', 'dept': 'HR'},
    {'name': 'Charlie', 'dept': 'Engineering'},
    {'name': 'Diana', 'dept': 'Marketing'},
    {'name': 'Eve', 'dept': 'HR'},
]

departments = {} # The dictionary to store the grouped data




# Loop through each employee record
for employee in employees:
    dept_name = employee['dept']
    employee_name = employee['name']




    # Check if the department key already exists in our dictionary
    if dept_name not in departments:



        # If not, create it with a new list containing the current employee's name
        departments[dept_name] = [employee_name]
    else:



        # If it exists, append the current employee's name to the existing list
        departments[dept_name].append(employee_name)

print(f"Employees by department: {departments}")



# Expected output: Employees by department: {'Engineering': ['Alice', 'Charlie'], 'HR': ['Bob', 'Eve'], 'Marketing': ['Diana']}




# A more advanced way using .setdefault() (as seen in one of the resources):
# departments_adv = {}
# for emp in employees:
#     departments_adv.setdefault(emp['dept'], []).append(emp['name'])
# print(f"Advanced method: {departments_adv}")

Conclusion

You've now covered the four most important data structures in Python. Mastering their unique behaviors and methods is a huge step toward writing clean, efficient, and professional-grade code.

Key Takeaways:

  • Lists ([]): Your go-to for an ordered, mutable sequence of items. Use when you need to add, remove, or reorder elements.
  • Tuples (()): Use for ordered, immutable data. Ideal for protecting data you don't want to change and for use as dictionary keys.
  • Sets ({} or set()): Use when you need a collection of unique items or need to perform mathematical set operations. They are fast for checking if an item is present.
  • Dictionaries ({k: v}): The best choice for storing key-value pairs. Perfect for structured data and fast lookups by a unique identifier.

In our next lesson, we will learn how to write functions. This will allow us to create reusable blocks of code that can take these data structures as inputs, process them, and return results, forming the building blocks of our future Django applications.