Get AI summaries of any video or article — Sign up free
Python Tutorial for Beginners 4: Lists, Tuples, and Sets thumbnail

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

Corey Schafer·
5 min read

Based on Corey Schafer's video on YouTube. If you like this content, support the original creators by watching, liking and subscribing to their content.

TL;DR

Lists are ordered and mutable, so they support indexing, slicing, and in-place updates.

Briefing

Python lists, tuples, and sets differ most in how they handle order, duplicates, and mutability—and those differences drive the right choice of data structure for common tasks like indexing, deduplication, and membership checks. Lists and tuples store sequential data, but lists are mutable while tuples are immutable. Sets store unordered collections that automatically remove duplicates, making them especially efficient for “is this value present?” and for comparing two collections.

Lists are created with square brackets and comma-separated values. Values are accessed by index starting at 0, with the last element at index length minus one. Python also supports negative indexing, where -1 always refers to the last item, avoiding index math when lists change size. Attempting to access an index that doesn’t exist raises an “index out of range” error. Lists can also be sliced using the colon syntax, where the start index is inclusive and the end index is exclusive—so “0:2” returns the first two items but stops before index 2. Slicing can omit the start or end to default to the beginning or end of the list.

Beyond reading values, lists support in-place modification through methods. append adds a single item to the end, while insert places a value at a specific index and shifts existing items. extend is for adding multiple items from another iterable; it adds each element individually, unlike insert, which can create a nested list if the inserted value is itself a list. Removal is handled with remove (delete by value) and pop (delete by position, defaulting to the last element). pop also returns the removed value, which is useful for stack-like behavior.

Lists can be reordered with reverse (flip order) and sort (alphabetical for strings, ascending for numbers). sort can take reverse=True to sort in descending order. If the goal is to get a sorted copy without changing the original list, sorted returns a new list rather than sorting in place. Built-ins like min, max, and sum compute aggregate values, and index finds the position of a value (raising an error if the value is missing). The in operator performs membership tests, returning True or False.

Loops integrate naturally with lists: a for loop iterates through items, and enumerate provides both index and value, optionally starting from 1. For converting between lists and strings, join combines list elements into a single string using a chosen separator, while split reverses the process by breaking a string into a list based on a delimiter.

Tuples look like lists but use parentheses and are immutable. Assigning one tuple variable to another creates shared reference behavior, but unlike lists, attempting item assignment triggers a TypeError because tuples don’t support mutation. As a result, tuples have fewer methods geared toward modification.

Sets use curly braces and automatically enforce uniqueness. Their iteration order is not reliable across runs because sets don’t care about ordering. Sets support membership tests efficiently, remove duplicates automatically, and compare collections using intersection (common elements), difference (elements in one set but not the other), and union (all unique elements from both). A key gotcha: {} creates an empty dictionary, not an empty set—an empty set must be created with the set() constructor.

Cornell Notes

Lists, tuples, and sets are core Python collection types with different rules. Lists are ordered and mutable, so they support indexing, slicing, and in-place changes via methods like append, insert, extend, remove, pop, reverse, and sort. Tuples are ordered like lists but immutable, so item assignment raises a TypeError; they’re best when values shouldn’t change. Sets are unordered and contain no duplicates, which makes them ideal for deduplication, fast membership tests using “in”, and set operations like intersection, difference, and union. Choosing the right structure depends on whether order matters, whether duplicates are allowed, and whether mutation is needed.

How do negative indexing and slicing work in Python lists, and why do they matter?

Negative indexing lets you access from the end of a list: index -1 is always the last element, regardless of list length. Slicing uses colon syntax with an inclusive start and exclusive stop—e.g., courses[0:2] returns items at indices 0 and 1 but not index 2. You can omit the start to begin at the list’s beginning (e.g., courses[:2]) or omit the stop to slice to the end (e.g., courses[2:]).

What’s the practical difference between append, insert, and extend when building or modifying lists?

append adds a single element to the end of the list (e.g., courses.append('Art') adds 'Art'). insert places one element at a specific index and shifts the rest (e.g., courses.insert(0,'Art') puts 'Art' at the front). extend adds multiple elements from an iterable by appending each element individually (e.g., courses.extend(courses2) merges the second list’s items into the first). Using insert with a list can create a nested list, while extend avoids that by flattening one level through iteration.

How do pop and remove differ for deleting items from a list?

remove deletes by value (e.g., courses.remove('math') removes the first matching 'math'). pop deletes by position and returns the removed value; by default it removes the last element (courses.pop()). This return value enables patterns like stack behavior: repeatedly pop until the list is empty, while capturing what was removed each time.

When should sorted be used instead of sort, and what do reverse=True and reverse do?

sort sorts a list in place, changing the original object. sorted returns a new sorted list without altering the original. For descending order, sort can take reverse=True (e.g., nums.sort(reverse=True)). reverse flips the current order of a list directly (e.g., courses.reverse()), which can be used after sorting or on its own.

Why are tuples treated differently from lists, and what error appears when trying to mutate a tuple?

Tuples are immutable, meaning their elements can’t be reassigned after creation. Attempting item assignment (like tuple_var[0] = ...) raises a TypeError: “tuple does not support item assignment.” This immutability reduces accidental changes and makes tuples suitable for fixed collections that are iterated over but not modified.

What makes sets useful compared with lists and tuples for membership and comparison?

Sets are unordered and automatically remove duplicates. They support membership tests efficiently using “in” (e.g., 'math' in courses_set). They also compare collections quickly: intersection returns shared elements, difference returns elements in one set but not the other, and union combines both while keeping uniqueness. Because order isn’t guaranteed, sets shouldn’t be relied on for positional access.

Review Questions

  1. What’s the difference between courses[0:2] and courses[0:3], and which indices are included or excluded?
  2. Give one scenario where extend is the correct choice over insert, and explain what would go wrong with insert.
  3. Why does {} create a dictionary rather than an empty set, and what constructor should be used instead?

Key Points

  1. 1

    Lists are ordered and mutable, so they support indexing, slicing, and in-place updates.

  2. 2

    Negative indexing (e.g., -1) reliably targets the last list element without needing the list length.

  3. 3

    Slicing uses inclusive start and exclusive stop, so courses[0:2] returns indices 0 and 1 only.

  4. 4

    append adds one element, insert adds one element at a position, and extend merges an iterable’s elements into the list.

  5. 5

    pop removes by index (default last) and returns the removed value; remove deletes by value.

  6. 6

    sort sorts in place while sorted returns a new list; sort(reverse=True) enables descending order.

  7. 7

    Sets are unordered, deduplicate automatically, and excel at membership tests and set operations like intersection, difference, and union.

Highlights

Negative indexing makes “last item” access stable even as lists grow: index -1 always points to the end.
extend merges elements from another iterable, while insert can create nested lists if the inserted value is itself a list.
sorted returns a new list without mutating the original, unlike sort which changes the list in place.
Tuples are immutable; trying to assign to tuple elements triggers a TypeError: “tuple does not support item assignment.”
{} creates an empty dictionary, not an empty set—use set() to create an empty set.

Topics