Accessing List Elements

6.2. Accessing List Elements#

Now that we know how to create lists, let’s learn how to access and extract data from them. Python provides several ways to retrieve elements from a list.

  • Understanding List Indices Lists in Python use zero-based indexing, meaning the first element is at position 0, the second at position 1, and so on. You can think of the index as the offset from the beginning of the list.

  • List Index Properties List indices work the same way as string indices:

    • Any integer expression can be used as an index.

    • If you try to read or write an element that does not exist, you get an IndexError.

    • If an index has a negative value, it counts backward from the end of the list, starting with -1.

import sys
from pathlib import Path

# Find project root by looking for _config.yml
current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent
        break
else:
    project_root = Path.cwd().parent.parent

# Add project root to path
sys.path.insert(0, str(project_root))

# Import shared teaching helpers and cell magics
from shared import thinkpython, diagram, jupyturtle, structshape
from shared.download import download

Below, we look at indexing (accessing a single element) and slicing (accessing a sublist) separately.

6.2.1. Indexing#

Indexing reads or writes a single element of a list using the bracket operator.

  • Syntax: lst[index]

  • Indices are 0-based: the first element is at index 0.

  • Negative indices count from the end: -1 is the last element, -2 is the one before that.

For example, if we have fruits = ['apple', 'banana', 'cherry'], then fruits[0] returns 'apple' and fruits[-1] returns 'cherry'.

fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
first = fruits[0]
last = fruits[-1]

print(f"First: {first}, Last: {last}")
First: apple, Last: elderberry

6.2.2. Slicing#

Slicing works with subsequences of a list using the syntax:

lst[start:stop], or

lst[start:stop:step].

  • start is the index where the slice begins (inclusive).

  • stop is the index where the slice ends (exclusive).

  • step controls how many positions to advance (defaults to 1). Use 2 to skip every other element, -1 to reverse.

  • If start is omitted, Python starts from the beginning of the list.

  • If stop is omitted, Python slices all the way to the end of the list.

  • Slicing does not modify the original list; it returns a new list containing the selected elements.

fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']

middle_three = fruits[1:4]      # elements at indices 1, 2, 3
from_start = fruits[:3]         # first three elements
to_end = fruits[2:]             # from index 2 to end
every_other = fruits[::2]       # step=2: every second element
reversed_fruits = fruits[::-1]  # step=-1: reverses the list

print(f"Middle three: {middle_three}")
print(f"From start: {from_start}")
print(f"To end: {to_end}")
print(f"Every other: {every_other}")
print(f"Reversed: {reversed_fruits}")
Middle three: ['banana', 'cherry', 'date']
From start: ['apple', 'banana', 'cherry']
To end: ['cherry', 'date', 'elderberry']
Every other: ['apple', 'cherry', 'elderberry']
Reversed: ['elderberry', 'date', 'cherry', 'banana', 'apple']

The step parameter in slicing enables powerful patterns like skipping elements, reversing, and extracting at intervals:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(f"Every other: {numbers[::2]}")
print(f"Every third: {numbers[::3]}")
print(f"Reversed: {numbers[::-1]}")
print(f"Every other, reversed: {numbers[::-2]}")
print(f"Slice from 1 to 8, step 2: {numbers[1:8:2]}")
print(f"Backwards from 7 to 2: {numbers[7:2:-1]}")     ### reversing
Every other: [0, 2, 4, 6, 8]
Every third: [0, 3, 6, 9]
Reversed: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Every other, reversed: [9, 7, 5, 3, 1]
Slice from 1 to 8, step 2: [1, 3, 5, 7]
Backwards from 7 to 2: [7, 6, 5, 4, 3]
### EXERCISE: Indexing and Slicing Practice
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
# 1. Get the third element (index 2)
# 2. Get the last element using negative indexing
# 3. Get a slice of elements from index 1 to 4 (not including 4)
# 4. Get every other element
### Your code starts here:



### Your code ends here.

Hide code cell source

# Solution
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
third = fruits[2]
last = fruits[-1]
slice_1_to_4 = fruits[1:4]
every_other = fruits[::2]

print(f"Third element: {third}")
print(f"Last element: {last}")
print(f"Slice [1:4]: {slice_1_to_4}")
print(f"Every other: {every_other}")
Third element: cherry
Last element: fig
Slice [1:4]: ['banana', 'cherry', 'date']
Every other: ['apple', 'cherry', 'elderberry']

6.2.3. Query Methods#

These methods help you find information about elements in a list without modifying it.

  • .count()

  • .index()

# count() - Returns number of times element appears
numbers = [1, 2, 3, 2, 4, 2, 5]
count = numbers.count(2)
print(f"The number 2 appears {count} times")

# index() - Returns index of first occurrence
letters = ['a', 'b', 'c', 'b', 'd']
position = letters.index('b')
print(f"First 'b' is at index: {position}")
The number 2 appears 3 times
First 'b' is at index: 1