Skip to content

Access List Item

diagram indexing raises, slicing does not mermaid
One square-bracket expression has two completely different error behaviours. A single index outside the list is an IndexError. A slice outside the list is clamped to what exists and returns whatever is left, which may be nothing at all -- so a wrong slice produces an empty list rather than a traceback, and the bug surfaces much later.
Section titled “Navigating Lists in Python: A Guide to Accessing List Items”

In Python, lists are a versatile and commonly used data structure for storing ordered collections of items. Understanding how to access elements within a list is fundamental to working with this data structure effectively. In this guide, we’ll explore the various methods and techniques for accessing list items in Python.

List indexing refers to the process of retrieving elements from a list based on their position. In Python, list indexing starts at 0, meaning the first element is at index 0, the second at index 1, and so on. Additionally, negative indices count from the end of the list, with -1 representing the last element.

Example:

list_indexing.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[0])
print(my_list[1])
print(my_list[2])
print(my_list[3])

Output:

command
C:\Users\username>python list_indexing.py
a
b
c
d

In the above example, we create a list of five elements and print the first four elements using their indices. Note that the last element is not printed because it has an index of 4, which is out of range for the list.

As mentioned above, negative indices count from the end of the list. For example, the last element of a list can be accessed using an index of -1, the second to last with an index of -2, and so on.

Example:

list_indexing.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[-1])
print(my_list[-2])
print(my_list[-3])
print(my_list[-4])

Output:

command
C:\Users\username>python list_indexing.py
e
d
c
b

In the above example, we create a list of five elements and print the last four elements using their negative indices. Note that the first element is not printed because it has an index of -5, which is out of range for the list.

The following diagram illustrates the indexing of a list with five elements:

list_indexing.py
my_list = ['a', 'b', 'c', 'd', 'e']
Element‘a’‘b’‘c’‘d’‘e’
Index01234
Index (Negative)-5-4-3-2-1

Multidimensional lists are lists that contain other lists as elements. In Python, multidimensional lists are accessed using multiple indices, with each index representing a different dimension of the list.

Example:

multidimensional_list.py
my_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
 
print(my_list[0][0])
print(my_list[1][1])
print(my_list[2][2])

Output:

command
C:\Users\username>python multidimensional_list.py
a
e
i

In the above example, we create a multidimensional list of three elements, each of which is a list of three elements. We then print the first element of the first list, the second element of the second list, and the third element of the third list.

List slices are a way of accessing a subset of a list. In Python, list slices are created using the syntax list[start:stop], where start is the index of the first element to include in the slice and stop is the index of the first element to exclude from the slice. If start is omitted, it defaults to 0, and if stop is omitted, it defaults to the length of the list.

Syntax:

syntax.py
list[start:stop]

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[1:3])

Output:

command
C:\Users\username>python list_slice.py
['b', 'c']

In the above example, we create a list of five elements and print a slice of the list from index 1 to index 3. Note that the element at index 3 is not included in the slice.

If the start index is omitted, it defaults to 0. This means that the slice will include all elements from the beginning of the list up to, but not including, the element at the stop index.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[:3])

Output:

command
C:\Users\username>python list_slice.py
['a', 'b', 'c']

In the above example, we create a list of five elements and print a slice of the list from index 0 to index 3. Note that the element at index 3 is not included in the slice.

my_list[:3] is equivalent to my_list[0:3].

If the stop index is omitted, it defaults to the length of the list. This means that the slice will include all elements from the start index to the end of the list.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[2:])

Output:

command
C:\Users\username>python list_slice.py
['c', 'd', 'e']

In the above example, we create a list of five elements and print a slice of the list from index 2 to the end of the list.

my_list[2:] is equivalent to my_list[2:len(my_list)].

If both the start and stop indices are omitted, the slice will include all elements in the list.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[:])

Output:

command
C:\Users\username>python list_slice.py
['a', 'b', 'c', 'd', 'e']

In the above example, we create a list of five elements and print a slice of the list from index 0 to the end of the list.

my_list[:] is equivalent to my_list[0:len(my_list)].

If the start index is negative, it will be interpreted as an offset from the end of the list. This means that the slice will include all elements from the element at the start index to the end of the list.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[-3:])

Output:

command
C:\Users\username>python list_slice.py
['c', 'd', 'e']

In the above example, we create a list of five elements and print a slice of the list from index -3 to the end of the list.

my_list[-3:] is equivalent to my_list[-3:len(my_list)].

If the stop index is negative, it will be interpreted as an offset from the end of the list. This means that the slice will include all elements from the beginning of the list up to, but not including, the element at the stop index.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[:-3])

Output:

command
C:\Users\username>python list_slice.py
['a', 'b']

In the above example, we create a list of five elements and print a slice of the list from index 0 to index -3. Note that the element at index -3 is not included in the slice.

my_list[:-3] is equivalent to my_list[0:-3].

Slicing with a Negative Start and Stop Index

Section titled “Slicing with a Negative Start and Stop Index”

If both the start and stop indices are negative, they will be interpreted as offsets from the end of the list. This means that the slice will include all elements from the element at the start index to the element at the stop index.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[-3:-1])

Output:

command
C:\Users\username>python list_slice.py
['c', 'd']

In the above example, we create a list of five elements and print a slice of the list from index -3 to index -1. Note that the element at index -1 is not included in the slice.

my_list[-3:-1] is equivalent to my_list[-3:len(my_list)-1].

The slice step is an optional third argument that specifies the number of elements to skip between each element in the slice. The default value is 1, meaning that each element in the slice will be included in the result. A value of 2 means that every other element will be included, and so on.

Syntax:

syntax.py
list[start:stop:step]

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[0:5:2])

Output:

command
C:\Users\username>python list_slice.py
['a', 'c', 'e']

In the above example, we create a list of five elements and print a slice of the list from index 0 to index 5 with a step of 2. This means that every other element will be included in the slice.

If the step is negative, the slice will be created in reverse order. This means that the start index must be greater than the stop index.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[4:0:-1])

Output:

command
C:\Users\username>python list_slice.py
['e', 'd', 'c', 'b']

In the above example, we create a list of five elements and print a slice of the list from index 4 to index 0 with a step of -1. This means that the slice will be created in reverse order.

Accessing List Items with a Negative Start Index and Positive Stop Index

Section titled “Accessing List Items with a Negative Start Index and Positive Stop Index”

If the start index is negative and the stop index is positive, the slice will be created in reverse order. This means that the start index must be greater than the stop index.

Example:

list_slice.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print(my_list[-1:3:-1])

Output:

command
C:\Users\username>python list_slice.py
['e', 'd', 'c']

In the above example, we create a list of five elements and print a slice of the list from index -1 to index 3 with a step of -1. This means that the slice will be created in reverse order.

The in operator is used to check if an element is present in a list. It returns True if the element is present and False otherwise.

Syntax:

syntax.py
element in list

Example:

in_operator.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print('a' in my_list)
print('f' in my_list)

Output:

command
C:\Users\username>python in_operator.py
True
False

In the above example, we create a list of five elements and check if the elements ‘a’ and ‘f’ are present in the list.

The not in operator is used to check if an element is not present in a list. It returns True if the element is not present and False otherwise.

Syntax:

syntax.py
element not in list

Example:

not_in_operator.py
my_list = ['a', 'b', 'c', 'd', 'e']
 
print('a' not in my_list)
print('f' not in my_list)

Output:

command
C:\Users\username>python not_in_operator.py
False
True

In the above example, we create a list of five elements and check if the elements ‘a’ and ‘f’ are not present in the list.

In this guide, we explored the various methods and techniques for accessing list items in Python. We also learned about list indexing, negative indexing, multidimensional lists, and list slices. Now that you understand how to access list items in Python, you can start working with lists more effectively in your programs. For more information on lists, check out Python’s official documentation.


sketch Watch a slice clamp instead of raising p5.js
The bar is a five-element list. The two handles are the start and stop of a slice, and they move outside the list on purpose. An index outside the list raises immediately; a slice outside it is trimmed to whatever exists and quietly returns fewer elements, or none. That is the whole difference, and it is why a bad slice is harder to find than a bad index.
pch.quizTag pch.quizDefaultTitle
  1. `L = [0,1,2,3,4]`. What does `L[10]` do, and what does `L[10:20]` do?

    pch.quizShowAnswer

    B — `L[10]` raises IndexError; `L[10:20]` returns `[]` — Indexing out of range raises immediately. Slicing clamps to what exists and returns whatever is left, which may be nothing. That asymmetry is why a bad index stops the program at the wrong line while a bad slice travels silently.

  2. `a = [0,1,2,3,4]`; `a[1:3] = [9]`. What is `a`?

    pch.quizShowAnswer

    A — `[0, 9, 3, 4]` — the list got shorter — Slice assignment does not have to preserve length. Two elements were replaced by one, so the list went from 5 items to 4. Assigning three items instead would have made it longer.

  3. What does `L[3:1]` return for a five-element list?

    pch.quizShowAnswer

    B — `[]` — The range runs backwards, so it selects nothing. Reversing needs a negative step: `L[3:1:-1]`.

  4. Why is an off-by-one in a slice harder to debug than one in an index?

    pch.quizShowAnswer

    B — The slice returns an empty list instead of raising, so the mistake surfaces somewhere else — No exception is raised at the wrong line. The empty result is passed onward and the failure appears in whatever consumed it, often several steps away.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading