Chapter 5: Lists, tuples, and sets
Introduces lists and tuples as Python sequence types and contrasts them with sets, where membership matters more than position.
After this chapter you will be able to
- Lists and tuples as sequences. Distinguish lists from tuples: both are Python sequence types, but tuples cannot be modified and can serve as basic records. Describe lists as more flexible and powerful than plain arrays without claiming specific operations not explained here.
- List creation and size. Describe a Python list as an ordered collection of objects, created with comma-separated elements in square brackets, whose size need not be fixed in advance.
- Length of nested lists. Explain what len returns for a list and how it treats a list nested inside that list.
- Positive and negative list indices. Explain how to retrieve a list element by index, using zero-based positions from the start or negative positions from the end.
- Slice boundaries and empty results. Describe what list[start:stop] extracts and what happens when the stop position precedes the start position.
- Index and slice assignment. Explain how assigning to a list index changes an element and how assigning to a slice replaces a range of elements, potentially changing the list’s length.
- Appending versus extending lists. Distinguish appending a single element from extending a list with the elements of another list.
- Position-based insertion and deletion. Describe how insert places an element before a specified position and how del removes an item or slice; relate both operations to slice assignment.
- In-place sorting and copies. Explain that a list’s sort() method changes the list itself, and describe how to sort without changing the original by using sorted() or sorting a copy made with [:].
- Custom sort keys. Explain how a key function changes list sorting from the default ordering, using word length as the example.
- Sorting with sorted. Explain how sorted() differs from a list’s sort method: it returns a sorted list from any iterable and accepts the same key and reverse parameters.
- List membership tests. Explain that `in` tests whether a value is in a list and returns a Boolean, while `not in` tests the inverse.
- List multiplication behavior. Explain that multiplying a list with * repeats it the specified number of times and joins the copies into a new list. Describe how a one-element list containing None can be used to create a list of a chosen size.
- List minimum and maximum. Explain what min and max return for a list and why they can raise an error for elements of different types.
- List position lookup with index. Explain that a list’s index method searches for an element equivalent to a given value and returns its position, unlike in, which only tests membership. Describe what happens when the value is absent and how to check before calling index.
- List count results. Explain that count searches a list for a given value and returns the number of matches, not their positions.
- Shared nested list references. Explain why changing a nested list through either of two variables can affect the same list, while assigning one variable a different list breaks that connection.
- Shallow versus deep copies. Distinguish shallow list copies from deep copies and apply that distinction when nested elements must be changed without affecting the original.
- Tuple immutability and purpose. Explain that tuples are similar to lists but cannot be modified after creation, and give dictionary keys as an example of a role tuples fill that lists cannot fill efficiently.
- Tuple immutability and contents. Explain what it means that tuples are immutable, while distinguishing a tuple itself from mutable objects it contains.
- One-element tuple comma. Explain why a one-element tuple needs a trailing comma, and distinguish it from an expression in parentheses and an empty tuple.
- Tuple packing and assignment. Explain how values on the right side of an assignment are packed into a tuple and unpacked into corresponding variables on the left, even without enclosing parentheses. Describe how this makes swapping variable values concise.
- Starred extended unpacking. Describe how a starred element handles surplus values during extended unpacking, including what it receives when there are none. State that packing and unpacking also work with lists.
- Sequence to list and tuple conversion. Explain how list and tuple convert sequences into new containers, and why applying list to a string produces a list of characters.
- Set purpose and ordering. Explain that a Python set is an unordered collection useful when membership and uniqueness are what matter.
- Set creation and membership. Explain how to create a set from a sequence, what happens to duplicates, and how to add, remove, or check for an element.
- Set combination operators. Distinguish the results of union, intersection, and symmetric difference for two sets, and name the operator shown for each.
- Frozen set membership. Explain why an ordinary set cannot be a member of another set, but a frozenset can.
- Temperature list summary. Describe how to find the highest, lowest, average, and median temperatures from the list, including that the median is the middle temperature after sorting.
- Independent practice before AI. Explain why the section recommends trying to solve the temperature exercise yourself before using an AI code generator.
- Focused code generation prompt. Explain why the prompt should describe only the remaining task rather than repeat the whole problem statement.
What it builds on
- Lists (chapter 3) · Introduces lists among Python’s built-in data types.
- Tuples (chapter 3) · Introduces tuples among Python’s built-in data types.
- Sets, frozensets (chapter 3) · Introduces sets among Python’s built-in data types.
- Function definition (chapter 3) · Introduces the idea of defining a function.
- Variables and assignments (chapter 4) · Assumes familiarity with variables and assignments.
Section by section
Introduction
Introduces lists and tuples as Python sequence types and contrasts them with sets, where membership matters more than position.
- Lists and tuples as sequences: Distinguish lists from tuples: both are Python sequence types, but tuples cannot be modified and can serve as basic records. Describe lists as more flexible and powerful than plain arrays without claiming specific operations not explained here.
Why it matters: This distinction gives you a starting point for choosing between the two sequence types. - Set membership over position: Explain that sets are useful when whether an object belongs to a collection matters more than where it sits in that collection.
Why it matters: It identifies the reason this chapter considers sets alongside sequence types.
Key terms: sequence types, lists, tuples, arrays, basic record type, sets, membership, position
5.1 Lists are like arrays
Introduces Python lists as ordered, resizable collections that can hold different kinds of objects, and explains how len counts their elements.
- List creation and size: Describe a Python list as an ordered collection of objects, created with comma-separated elements in square brackets, whose size need not be fixed in advance.
Why it matters: This gives you the basic model for creating and working with lists. - Mixed list element types: Explain what kinds of objects a Python list can contain, including whether its elements must all have the same type.
Why it matters: You need not choose a single element type when putting objects in a list. - Length of nested lists: Explain what len returns for a list and how it treats a list nested inside that list.
Why it matters: This prevents you from mistaking a nested list's contents for extra elements of the outer list.
Key terms: list, ordered collection, square brackets, list element, Python object, len function, nested list
5.2 List indices
This section explains how to access individual list elements and use slices to extract or copy portions of a list.
- Positive and negative list indices: Explain how to retrieve a list element by index, using zero-based positions from the start or negative positions from the end.
Why it matters: These two ways of counting let you select elements from either end of a list. - Slice boundaries and empty results: Describe what list[start:stop] extracts and what happens when the stop position precedes the start position.
Why it matters: Knowing which boundary is excluded helps you predict exactly what a slice returns. - Omitted slice bounds and copies: Explain the meaning of leaving out either or both slice indices, including how a full slice can be used to copy a list.
Why it matters: A full slice gives you a list you can modify without changing the original list.
Key terms: list indices, negative numbers, slicing, sublist, copies the list
5.3 Modifying lists
This section explains how to change a list by assigning to indices or slices and by using methods to add, remove, or reorder elements.
- Index and slice assignment: Explain how assigning to a list index changes an element and how assigning to a slice replaces a range of elements, potentially changing the list’s length.
Why it matters: Index and slice assignment let you change existing list contents, including replacing a range with a different number of elements. - Appending versus extending lists: Distinguish appending a single element from extending a list with the elements of another list.
Why it matters: Choosing between append and extend determines whether another list becomes one element or contributes its elements individually. - Position-based insertion and deletion: Describe how insert places an element before a specified position and how del removes an item or slice; relate both operations to slice assignment.
Why it matters: These readable operations let you add or delete elements at positions while showing how slice assignment can do the same work. - Value-based removal behavior: Explain how remove chooses an item to delete and what happens if the value is absent.
Why it matters: remove is useful when you have a value rather than its position, but an absent value needs care. - In-place list reversal: State what the reverse method does to a list.
Why it matters: reverse changes the order of the existing list directly.
Key terms: list index notation, slice notation, slice assignment, append, extend, insert, del, remove, first instance, in
5.4 Sorting lists
This section explains how list sorting changes a list, how to preserve the original, and what determines the default and optional sort order.
- In-place sorting and copies: Explain that a list’s sort() method changes the list itself, and describe how to sort without changing the original by using sorted() or sorting a copy made with [:].
Why it matters: Choosing between sorting a list and preserving it prevents unintended changes to your data. - Default sort comparisons: Describe what the default sort can sort and how it orders a list of lists, including why a list mixing numbers and strings raises an exception.
Why it matters: Knowing what Python compares helps you predict a sort’s result or recognize why it fails. - Optional sort ordering: State that reverse=True makes sort use reverse order and that a custom key function can determine how elements are sorted.
Why it matters: These options show that sorting need not be limited to the default order.
Key terms: sort method, in-place sort, sorted(), slice, [:], comparable types, default key method, list of lists, exception, reverse
5.4.1 Custom sorting
This section explains how to sort lists by a custom key, when a lambda can supply that key, and why descending order does not need a custom sort.
- Custom sort keys: Explain how a key function changes list sorting from the default ordering, using word length as the example.
Why it matters: A sort key lets you order items by a property other than their default comparison. - Inline lambda sort keys: Describe how a short lambda can replace a separately named sort-key function and why the section suggests using one.
Why it matters: For a short, one-use sort key, a lambda keeps the ordering rule beside the sort call. - Descending order and sort cost: Distinguish sorting in descending order from custom key sorting, and explain the performance caution about custom keys.
Why it matters: It helps you avoid an unnecessary custom key when you only need to reverse the ordering.
Key terms: sort method, key, key function, lexicographical order, len, lambda function, anonymous, sort key, len(x), custom sorting
5.4.2 The sorted () function
This section introduces sorted() for sorting any iterable and asks readers to apply a key function to sort nested lists.
- Sorting with sorted: Explain how sorted() differs from a list’s sort method: it returns a sorted list from any iterable and accepts the same key and reverse parameters.
Why it matters: You can sort values from an iterable even when it has no sort method. - Nested list sort key: Apply a key function that selects the second element of each inner list to produce the ordering shown in the exercise.
Why it matters: A key function lets you choose which part of each item determines its order.
Key terms: sorted(), iterable, key, reverse, sort method, sort() method
5.5 Other common list operations
5.5.1 List membership with the in operator
This subsection shows how to test whether a value is present or absent in a list.
- List membership tests: Explain that `in` tests whether a value is in a list and returns a Boolean, while `not in` tests the inverse.
Why it matters: These operators let you check list membership directly.
Key terms: in operator, not in operator, Boolean value
5.5.2 List concatenation with the + operator
5.5.3 List initialization with the * operator
This section explains how list multiplication creates a list of a chosen size and why sizing a list in advance can be efficient.
- List multiplication behavior: Explain that multiplying a list with * repeats it the specified number of times and joins the copies into a new list. Describe how a one-element list containing None can be used to create a list of a chosen size.
Why it matters: This gives you a way to create a list at the size you need. - Advance list sizing efficiency: Justify using list multiplication when a large list's size is known ahead of time, rather than growing it with append.
Why it matters: Sizing a large list up front can avoid the overhead of expanding it later.
Key terms: list multiplication operator, None, append, memory reallocation overhead
5.5.4 List minimum or maximum with min and max
This subsection explains how min and max find a list’s smallest and largest elements and when comparisons can fail.
- List minimum and maximum: Explain what min and max return for a list and why they can raise an error for elements of different types.
Why it matters: You can use these functions beyond numbers, provided the elements can be meaningfully compared.
Key terms: min, max, list, error
5.5.5 List search with index
This subsection explains how to find a value’s position in a list and what happens if the value is absent.
- List position lookup with index: Explain that a list’s index method searches for an element equivalent to a given value and returns its position, unlike in, which only tests membership. Describe what happens when the value is absent and how to check before calling index.
Why it matters: It helps you choose between checking whether a value is present and finding where it is, without an unexpected error.
Key terms: index method, in, list element
5.5.6 List matches with count
This subsection explains that list count returns how many times a value occurs, rather than where it occurs.
- List count results: Explain that count searches a list for a given value and returns the number of matches, not their positions.
Why it matters: It helps you choose the operation that answers how often a value appears, rather than where it appears.
Key terms: count, list, value, positional information
5.5.7 Summary of list operations
This subsection points readers to a reference table of list operations and offers practice questions, but does not explain a new concept.
5.6 Nested lists and deep copies
The section explains nested lists, shared references to mutable objects, and why a deep copy is needed to change nested elements independently.
- Nested list indexing: Describe how nested lists can represent two-dimensional matrices and how two indices identify a member.
Why it matters: Nested indexing lets you describe which value in a matrix you want. - Shared nested list references: Explain why changing a nested list through either of two variables can affect the same list, while assigning one variable a different list breaks that connection.
Why it matters: It explains why changing a value and assigning a new list can have different effects. - Shallow versus deep copies: Distinguish shallow list copies from deep copies and apply that distinction when nested elements must be changed without affecting the original.
Why it matters: Choosing the right kind of copy prevents unexpected changes to the original nested data.
Key terms: nested lists, two-dimensional matrices, two-dimensional indices, variables, objects, mutable, nested list, full slice, shallow copy, deep copy
5.7 Tuples
Introduces tuples as list-like structures that cannot be modified and explains why Python includes them.
- Tuple immutability and purpose: Explain that tuples are similar to lists but cannot be modified after creation, and give dictionary keys as an example of a role tuples fill that lists cannot fill efficiently.
Why it matters: This distinction explains why Python has tuples as well as lists.
Key terms: tuples, lists, keys for dictionaries
5.7.1 Tuple basics
This section introduces tuple creation and use, then explains how immutability affects contained objects and copying.
- Tuple creation and use: Describe how to create a tuple and how its basic use resembles a list. State that + and * can create tuples from existing ones.
Why it matters: The familiar list-like behavior makes tuples easier to start using. - Tuple immutability and contents: Explain what it means that tuples are immutable, while distinguishing a tuple itself from mutable objects it contains.
Why it matters: Immutability is the main distinction from lists, but it does not freeze mutable objects held inside a tuple. - Tuple copies and aliases: Explain why the shallow-copy methods described here yield aliases rather than new tuple objects, and why those aliases can serve as copies in practice.
Why it matters: It explains why an apparent tuple copy may share the original object without losing practical usefulness.
Key terms: tuple, list, +, *, immutable, mutable objects, dictionary keys, shallow copy, alias
5.7.2 One-element tuples need a comma
This section explains why a one-element tuple needs a trailing comma to distinguish it from a parenthesized expression.
- One-element tuple comma: Explain why a one-element tuple needs a trailing comma, and distinguish it from an expression in parentheses and an empty tuple.
Why it matters: The comma lets you express a one-element tuple without confusing it with ordinary expression grouping.
Key terms: one-element tuple, comma, parentheses, empty tuple
5.7.3 Packing and unpacking tuples
This section explains how Python assigns values by packing and unpacking tuples, including starred unpacking for surplus values.
- Tuple packing and assignment: Explain how values on the right side of an assignment are packed into a tuple and unpacked into corresponding variables on the left, even without enclosing parentheses. Describe how this makes swapping variable values concise.
Why it matters: It lets you read and write assignments that distribute several values at once. - Starred extended unpacking: Describe how a starred element handles surplus values during extended unpacking, including what it receives when there are none. State that packing and unpacking also work with lists.
Why it matters: It explains where extra values go when an unpacking assignment includes a starred element.
Key terms: packing, unpacking, tuple, extended unpacking, starred element, list
5.7.4 Converting between lists and tuples
This subsection shows how to make a new list or tuple from a sequence, including how to turn a string into a list of characters.
- Sequence to list and tuple conversion: Explain how list and tuple convert sequences into new containers, and why applying list to a string produces a list of characters.
Why it matters: You can choose a list or tuple representation for sequence elements without changing the original sequence.
Key terms: list function, tuple function, sequence, string
5.8 Sets
Defines Python sets by their unordered, membership-and-uniqueness-focused nature and identifies which objects can be set members.
- Set purpose and ordering: Explain that a Python set is an unordered collection useful when membership and uniqueness are what matter.
Why it matters: This helps you recognize when a set fits the information you need to track. - Eligible set members: State that set members must be immutable and hashable, and distinguish the allowed examples from the disallowed ones given here.
Why it matters: The membership rule tells you which kinds of objects you can put in a set.
Key terms: set, unordered, membership, uniqueness, immutable, hashable, set members, dictionary keys
5.8.1 Set operations
This section shows how to create and change sets, test membership, and combine sets with union, intersection, and symmetric difference.
- Set creation and membership: Explain how to create a set from a sequence, what happens to duplicates, and how to add, remove, or check for an element.
Why it matters: These operations let you keep distinct elements and check whether one is present. - Set combination operators: Distinguish the results of union, intersection, and symmetric difference for two sets, and name the operator shown for each.
Why it matters: Each operator answers a different question about how two sets overlap.
Key terms: set, sequence, add, remove, in, union, intersection, symmetric difference, |, &
5.8.2 Frozen sets
This subsection explains why frozen sets, unlike ordinary sets, can be members of other sets.
- Frozen set membership: Explain why an ordinary set cannot be a member of another set, but a frozenset can.
Why it matters: It helps you choose a frozen set when a collection itself needs to be an element of a set.
Key terms: set, frozenset, immutable, hashable
5.9 Lab: Examining a list
This lab asks the reader to summarize a list of monthly temperature readings using basic list operations.
- Temperature list summary: Describe how to find the highest, lowest, average, and median temperatures from the list, including that the median is the middle temperature after sorting.
Why it matters: These are common ways to summarize data held in a list.
Key terms: list, mean, median, min(), max(), sum()
5.9.1 Why solve it the old-fashioned way?
This section asks readers to try the temperature-list exercise themselves before using AI, explaining how that practice improves their ability to prompt for and evaluate generated code.
- Independent practice before AI: Explain why the section recommends trying to solve the temperature exercise yourself before using an AI code generator.
Why it matters: Trying the exercise yourself makes AI more useful because you can ask for what you need and judge what it gives you. - Temperature exercise starting point: Describe what the provided code supplies for the temperature exercise and the approach the section suggests for answering its questions.
Why it matters: Knowing what the starter code already provides lets you focus on working with the temperature values.
Key terms: AI code generator, effective prompt, generated code, list of floats, unique values
5.9.2 Solving the problem with AI code generation
This subsection shows how to request AI-generated code for the list-examining lab by writing a focused prompt in Colaboratory.
- Focused code generation prompt: Explain why the prompt should describe only the remaining task rather than repeat the whole problem statement.
Why it matters: A focused request tells the generator which part of the lab still needs code. - Colaboratory generation workflow: Describe how to submit a code-generation prompt in Colaboratory and what to do with the resulting code.
Why it matters: Generating code is a starting point; the reader still needs to check whether it meets the request.
Key terms: prompt, list, floats, Colaboratory, Generate
5.9.3 Solutions and discussion
5.10 Summary
Where this is used later
- Strings as sequences of characters (chapter 6) · Applies index notation previously used with lists.
- Modifying strings with list manipulations (chapter 6) · Manipulating lists
- Word counting (chapter 7) · Sorting lists provides background for ordering the tuples.
- Sorting (chapter 21) · List sorting methods and the sorted() function.
- lambda expressions (chapter 9) · Develops lambda expressions beyond this brief sorting example.
- Generator functions (chapter 9) · Earlier use of in introduces membership checks.
- Sparse matrices (chapter 7) · Provides a list-based way to think about matrices before considering sparse matrices.
- Other dictionary operations (chapter 7) · The introduction to shallow and deep copies.
Concepts explained in this chapter
- list()The list function is a Python built-in constructor that creates a new list from an iterable or sequence of elements.
- tupleA tuple is an ordered, immutable collection that can contain multiple values, including values of different types.
- code generationCode generation is the automated production of source code from prompts, specifications, templates, or other inputs.
- promptA prompt is an instruction or input supplied to an AI system to elicit a particular response or generated output.
- slicingSlicing selects or partitions a portion of an indexed sequence or multidimensional array, often along specified indices or dimensions.
- sortedsorted is a Python built-in function that returns a new list containing the items of an iterable in sorted order.
- key functionA key function is a callable that maps each item to a value used to determine that item's ordering during sorting.
- sorting algorithmA sorting algorithm is a procedure that rearranges elements of a collection into an order determined by an ordering criterion.
- copyCopying is the creation of a separate representation of an existing value, object, or data, preserving some or all of its contents or state.
- meanA mean is a measure of central tendency, calculated as the arithmetic average of values or, for a random variable, as the probability-weighted average of its possible values.
- lambdaA lambda expression is an anonymous function expression that evaluates to a function value and returns the value of its expression body.
- built-in functionappend is a Python list method that adds one object to the end of a list.
- del statementA del statement is Python syntax for deleting names, items, or slices from objects that support deletion.
- reversingThe reverse method is a Python list operation that reverses the order of elements in the list in place.
- conversational aiA chatbot is software that conducts conversational interactions with users through natural-language input and output.
- membership operatorThe in operator is a Python comparison operator that tests whether a value is contained in a collection.
- deep copyA deep copy is a recursively independent copy of a container and the modifiable objects nested within it.
- immutable collectionImmutability is the property of an object or data structure that prevents its contents from being changed after creation.
- assignmentAssignment is a programming-language operation that binds or stores an evaluated value in a variable, property, or other assignable location.
- commentA comment is source text ignored during program execution that explains or annotates code for human readers.
- whitespace characterWhitespace is non-printing character spacing, such as spaces, tabs, and line breaks, that can separate or structure source code.
- Google ColabGoogle Colaboratory is a hosted notebook platform that provides browser-based interactive computing environments, commonly with Python support.
- bindingA binding is an association between an identifier and an object in a namespace.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
