In Python, there are two main ways to access elements in a list. The first approach is to use indices, and the second one is to use list slicing. Let’s explore them one by one in this practical, example-based article.
Accessing elements by index
Using positive index
Lists in Python are zero-based index. That means the first element of a list has an index of 0
, the second element has an index of 1
, and so on.
Using indexing allows you direct access to an individual element by its index position, as shown below:
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Accessing the element at index 2
element = my_list[2]
print(element)
Output:
3
Using negative index
You can access elements from the end of a list without knowing the exact length.
Example:
# Creating a list
my_list = ["Programming", "Python", "Sling Academy"]
# # Accesses the last element in the list
last_element = my_list[-1]
print(last_element)
Output:
Sling Academy
List slicing
Slicing a list in Python helps you extract a portion of the list by specifying a range of indices. It provides a flexible way to access multiple elements at once.
To slice a list, use the colon (:
) notation to define a range of indices for the slice. The slice notation follows the pattern [start:stop:step]
, where start
is the starting index (inclusive), stop
is the stopping index (exclusive), and step
is the increment size (optional).
Basic example:
# Creating a list
my_list = ['one', 'two', 'three', 'four', 'five']
# Retrieves elements from index 1 (inclusive) to 4 (exclusive)
subset = my_list[1:4]
print(subset)
Output:
['two', 'three', 'four']
In this example, the slice my_list[1:4]
returns a new list containing elements from index 1
up to, but not including, index 4
.
Remember that Python lists are zero-based index. That’s why the first element in the resulting list is two
.
Another example:
# Creating a list
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Retrieves elements from index 1 to 9 with a step size of 2
subset = my_list[1:9:2]
print(subset)
Output:
[1, 3, 5, 7]
In the code snippet above, the slice my_list[1:9:2]
returns a new list containing elements from index 1
to 9
with a step size of 2
, effectively selecting every second element within that range.