Access List Item
flowchart TD
A["L[...] on a 5-element list"] --> B{"one index, or a slice?"}
B -->|"L[10]"| C["IndexError -- immediate and obvious"]
B -->|"L[10:20]"| D["[] -- silently empty"]
B -->|"L[3:1]"| E["[] -- the range runs backwards"]
B -->|"L[-10:99]"| F["the whole list -- both ends clamped"]
D --> G["no exception, so the mistake travels"]
E --> G
H["L[::-1]"] --> I["reversed copy"]
J["L[1:3] = [9]"] --> K["slice assignment can CHANGE the length"]
Navigating Lists in Python: A Guide to Accessing List Items
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.
Basics of List Indexing
Section titled “Basics of List Indexing”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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[0])
print(my_list[1])
print(my_list[2])
print(my_list[3])Output:
C:\Users\username>python list_indexing.py
a
b
c
dIn 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.
Negative Indexing
Section titled “Negative Indexing”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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[-1])
print(my_list[-2])
print(my_list[-3])
print(my_list[-4])Output:
C:\Users\username>python list_indexing.py
e
d
c
bIn 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.
Diagram of List Indexing
Section titled “Diagram of List Indexing”The following diagram illustrates the indexing of a list with five elements:
my_list = ['a', 'b', 'c', 'd', 'e']| Element | ‘a’ | ‘b’ | ‘c’ | ‘d’ | ‘e’ |
|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 |
| Index (Negative) | -5 | -4 | -3 | -2 | -1 |
Accessing Multidimensional Lists
Section titled “Accessing Multidimensional Lists”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:
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:
C:\Users\username>python multidimensional_list.py
a
e
iIn 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.
Accessing List Slices
Section titled “Accessing List Slices”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:
list[start:stop]Example:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[1:3])Output:
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.
Omitting the Start Index
Section titled “Omitting the Start Index”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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[:3])Output:
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].
Omitting the Stop Index
Section titled “Omitting the Stop Index”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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[2:])Output:
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)].
Ommiting Both Indices
Section titled “Ommiting Both Indices”If both the start and stop indices are omitted, the slice will include all elements in the list.
Example:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[:])Output:
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)].
Slicing with a Negative Start Index
Section titled “Slicing with a Negative Start Index”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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[-3:])Output:
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)].
Slicing with a Negative Stop Index
Section titled “Slicing with a Negative Stop Index”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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[:-3])Output:
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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[-3:-1])Output:
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].
Slice Step
Section titled “Slice Step”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:
list[start:stop:step]Example:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[0:5:2])Output:
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.
Accessing List Items with a Negative Step
Section titled “Accessing List Items with a Negative Step”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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[4:0:-1])Output:
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:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[-1:3:-1])Output:
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.
in Operator
Section titled “in Operator”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:
element in listExample:
my_list = ['a', 'b', 'c', 'd', 'e']
print('a' in my_list)
print('f' in my_list)Output:
C:\Users\username>python in_operator.py
True
FalseIn the above example, we create a list of five elements and check if the elements ‘a’ and ‘f’ are present in the list.
not in Operator
Section titled “not in Operator”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:
element not in listExample:
my_list = ['a', 'b', 'c', 'd', 'e']
print('a' not in my_list)
print('f' not in my_list)Output:
C:\Users\username>python not_in_operator.py
False
TrueIn the above example, we create a list of five elements and check if the elements ‘a’ and ‘f’ are not present in the list.
Conclusion
Section titled “Conclusion”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.
Check yourself
Section titled “Check yourself”-
`L = [0,1,2,3,4]`. What does `L[10]` do, and what does `L[10:20]` do?
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.
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.
-
`a = [0,1,2,3,4]`; `a[1:3] = [9]`. What is `a`?
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.
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.
-
What does `L[3:1]` return for a five-element list?
The range runs backwards, so it selects nothing. Reversing needs a negative step: `L[3:1:-1]`.
pch.quizShowAnswer
B — `[]` — The range runs backwards, so it selects nothing. Reversing needs a negative step: `L[3:1:-1]`.
-
Why is an off-by-one in a slice harder to debug than one in an index?
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.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.
Try it: Access List Elements Exercises
Section titled “Try it: Access List Elements Exercises”Exercise 1 – Positive Indexing
Section titled “Exercise 1 – Positive Indexing”Exercise 2 – Negative Indexing
Section titled “Exercise 2 – Negative Indexing”Exercise 3 – Slicing a List
Section titled “Exercise 3 – Slicing a List”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading