Concepts / Creating and Indexing Lists

Creating and Indexing Lists

The nested list is one element of the outer list, even though it contains two values of its own.

  • Programming

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.

python
Output
['a', 'b', ['c', 'd']]
python
Output
['a', 'b', 'c', 'd']

What do you think happens?

What would the list contain after starting with ['a', 'b'] and calling append(['c', 'd'])?

  • ['a', 'b', 'c', 'd']

  • ['a', 'b', ['c', 'd']]

  • ['a', 'b']

Reveal answer
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

Definition

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.

python

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.

python
Output
'spam'
5
[10, 20]
0'spam'12.0253[10, 20]
Which element does each index refer to, including the nested list as one outer-list element?

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.

Code walkthrough
t = ['a', 'b']
t.append(['d', 'e'])
print(t)
print(t[2])
  1. 1
    Line 1 creates a list containing 'a' and 'b'.
  2. 2
    Line 2 appends one argument. That argument is itself a list, so it occupies one position in t.
  3. 3
    Line 3 displays the outer list.
  4. 4
    Line 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.
Output
['a', 'b', ['d', 'e']]
['d', 'e']
t['a', 'b', ['d', 'e']]'a''b'['d', 'e']one elementcontainscontainscontains
What does the outer list contain after another list is appended as one element?

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.

Code walkthrough
t = ['a', 'b']
t.extend(['d', 'e'])
print(t)
print(t[2])
  1. 1
    Line 1 creates the starting list.
  2. 2
    Line 2 extends t with two individual elements.
  3. 3
    Line 3 displays the four-element list.
  4. 4
    Line 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.
Output
['a', 'b', 'd', 'e']
'd'
['a', 'b']['a', 'b', ['d','e']]['a', 'b', 'd', 'e']append(['d', 'e'])extend(['d', 'e'])
How does the list structure change when append stores the argument as one element compared with extend adding each item separately?

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.

python
After operationList stateElement 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.

fruit['apple', 'banana']append3 elementsextend5 elementsappend6 elements'orange'['grape', 'kiwi']['mango', 'peach']
What is the list's state after each call, and at which step does the final nested structure appear?

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.

python
Output
['first', 'second', 'third']

Mistakes Beginners Make

  • Common mistake

    Expecting append to unpack a list

    What it looks like
    items = [1, 2]; items.append([3, 4])
    Why it fails

    append treats [3, 4] as one argument and therefore one element.

    Do this instead

    Use extend([3, 4]) when 3 and 4 should become separate elements.

  • Common mistake

    Expecting extend to create a nested list

    What it looks like
    items = [1, 2]; items.extend([3, 4])
    Why it fails

    extend unpacks the argument and adds its elements individually.

    Do this instead

    Use 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 like
    items = ['a', 'b', ['c', 'd']]
    Why it fails

    The nested list is one element of items, so the outer list has three elements.

    Do this instead

    Treat 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 like
    result = items.append('new')
    Why it fails

    append and extend modify the original list in place and return None.

    Do this instead

    Inspect items after the call.

Practice the Structure

EASY

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.
Worked example

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.

  1. 1
    Choose the operation

    Use extend because the elements of the second list should be added individually.

  2. 2
    Trace the structure

    The original two elements remain first, followed by each element from the second list.

  3. 3
    Check the index

    The first newly added element occupies the next available index, while the second newly added element follows it.

Result

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

  1. 1
    A list is a sequence that can contain values of different data types, including other lists.
  2. 2
    Square brackets create lists; [] creates an empty list.
  3. 3
    Indexes identify positions in a list, and a nested list occupies one position in its outer list.
  4. 4
    append adds its argument as one element, while extend adds the elements of an iterable individually.
  5. 5
    Both 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.

Related concepts

More concepts starting with C