Creating and Indexing Lists
The nested list is one element of the outer list, even though it contains two values of its own.
A Small Change with a Big Difference
Python provides two methods for adding elements to a list: append and extend. Both add something at the end of the original list, but they incorporate their arguments differently. The most reliable way to learn the difference is to watch the list after each operation.
['a', 'b', ['c', 'd']]['a', 'b', 'c', 'd']What do you think happens?
What would the list contain after starting with ['a', 'b'] and calling append(['c', 'd'])?
Reveal answer
['a', 'b', ['c', 'd']]
append treats its argument as one element. The argument is a list, so that complete list occupies one new position inside the outer list.
List Structure and Index Positions
A list is a sequence of values that can contain any data type. Lists are created with square brackets, with elements separated by commas. A string, by contrast, contains characters. A list may contain integers, strings, floats, or other lists in the same structure.
The list mixed has four elements: the string 'spam', the float 2.0, the integer 5, and the nested list [10, 20]. The nested list is one element of the outer list, even though it contains two values of its own.
'spam'
5
[10, 20]Appending One Element
append adds its argument as one indivisible element at the end of the list. It does not matter whether the argument is a number, a string, or another list. If the argument is another list, the complete list becomes a nested element.
t = ['a', 'b']
t.append(['d', 'e'])
print(t)
print(t[2])- 1Line 1 creates a list containing 'a' and 'b'.
- 2Line 2 appends one argument. That argument is itself a list, so it occupies one position in t.
- 3Line 3 displays the outer list.
- 4Line 4 accesses the nested list at index 2.
- The variable t refers to a list with two elements.
- append adds the argument ['d', 'e'] as one new element.
- The resulting list has three elements.
- Index 2 refers to the complete nested list.
['a', 'b', ['d', 'e']]
['d', 'e']Extending with Multiple Elements
extend takes an iterable, unpacks it, and adds each of its elements separately to the end of the list. When the argument is a list, its contents are merged into the original list rather than stored as one nested list.
t = ['a', 'b']
t.extend(['d', 'e'])
print(t)
print(t[2])- 1Line 1 creates the starting list.
- 2Line 2 extends t with two individual elements.
- 3Line 3 displays the four-element list.
- 4Line 4 accesses the first element added by extend.
- The variable t starts with two elements.
- extend takes the two elements from ['d', 'e'] separately.
- The resulting list has four elements.
- Index 2 refers to 'd', not to the complete argument list.
['a', 'b', 'd', 'e']
'd'Tracing a List-Building Sequence
Tracing means recording the list after each operation instead of looking only at the final result. This makes it easier to find the exact line where your expectation and the actual structure diverge.
| After operation | List state | Element count |
|---|---|---|
| append('orange') | ['apple', 'banana', 'orange'] | 3 |
| extend(['grape', 'kiwi']) | ['apple', 'banana', 'orange', 'grape', 'kiwi'] | 5 |
| append(['mango', 'peach']) | ['apple', 'banana', 'orange', 'grape', 'kiwi', ['mango', 'peach']] | 6 |
The nested list in the final row counts as one element of fruit.
Names, Lists, and Practical Choices
You can assign a list to a variable just as you assign numbers or strings. The variable name refers to the entire list, so an operation written after that name works on that list. For example, fruit.append('orange') changes the list referred to by fruit.
['first', 'second', 'third']Mistakes Beginners Make
Common mistake Expecting append to unpack a list
What it looks likeitems = [1, 2]; items.append([3, 4])Why it failsappend treats [3, 4] as one argument and therefore one element.
Do this insteadUse extend([3, 4]) when 3 and 4 should become separate elements.
Common mistake Expecting extend to create a nested list
What it looks likeitems = [1, 2]; items.extend([3, 4])Why it failsextend unpacks the argument and adds its elements individually.
Do this insteadUse append([3, 4]) when the complete list [3, 4] should be one nested element.
Common mistake Counting values inside a nested list as separate outer-list positions
What it looks likeitems = ['a', 'b', ['c', 'd']]Why it failsThe nested list is one element of items, so the outer list has three elements.
Do this insteadTreat the nested list as one outer position, accessible at index 2.
Common mistake Looking for a returned list instead of checking the modified list
What it looks likeresult = items.append('new')Why it failsappend and extend modify the original list in place and return None.
Do this insteadInspect items after the call.
Practice the Structure
Start with values = ['x']. Decide which method belongs in each blank so the final list is ['x', 'y', 'z'] rather than ['x', ['y', 'z']]. Then identify the value at index 2.
Hints
- The desired result has 'y' and 'z' as separate elements.
- Use the method that adds the elements of a collection individually.
- Count the positions after the operation.
Selecting the Correct List Operation
You have a list of two names and another list containing two more names. You want all four names to be separate elements of the original list.
- 1Choose the operation
Use extend because the elements of the second list should be added individually.
- 2Trace the structure
The original two elements remain first, followed by each element from the second list.
- 3Check the index
The first newly added element occupies the next available index, while the second newly added element follows it.
Use extend when a collection should be merged into the original list as separate elements. Use append when that collection should remain one nested element.
Key Takeaways
- 1A list is a sequence that can contain values of different data types, including other lists.
- 2Square brackets create lists; [] creates an empty list.
- 3Indexes identify positions in a list, and a nested list occupies one position in its outer list.
- 4append adds its argument as one element, while extend adds the elements of an iterable individually.
- 5Both methods modify the original list in place and return None.
At a glance
- Lists use square brackets and may contain mixed data types, empty contents, or nested lists.
- A nested list is one element of its outer list.
- append adds one argument as one new element.
- extend unpacks an iterable and adds its elements separately.
- Trace the list after every operation to predict indexes and detect unexpected nesting.