SoFunction
Updated on 2025-03-10

Share advanced indexing skills for lists in Python

Lists are one of the most commonly used data structures in Python, which allows you to store multiple elements and can access them through indexes. This article will take you into the advanced indexing skills of Python lists, making you more handy when processing data.

1. Basic index

First, let's take a look at how to use basic indexes to access elements in a list.

# Create a simple listfruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']

# Access the first elementprint(fruits[0])  # Output: apple
# Access the last elementprint(fruits[-1])  # Output: elderberry
# Access the third elementprint(fruits[2])  # Output: cherry

2. Slice

Slicing is a very powerful feature in Python lists that can be used to get part of a list.

# Get the first three elementsprint(fruits[:3])  # Output: ['apple', 'banana', 'cherry']
# Get from the second element to the fourth elementprint(fruits[1:4])  # Output: ['banana', 'cherry', 'date']
# Get from the third element to the last elementprint(fruits[2:])  # Output: ['cherry', 'date', 'elderberry']

3. Negative index slice

Negative indexes can also be used for slices, which is very useful when dealing with elements at the end of a list.

# Get the last two elementsprint(fruits[-2:])  # Output: ['date', 'elderberry']
# Get the third to the last elementprint(fruits[-3:-1])  # Output: ['cherry', 'date']

4. Step length

The step size parameter allows you to get elements in the list at specified intervals.

# Get every other elementprint(fruits[::2])  # Output: ['apple', 'cherry', 'elderberry']
# Start with the last element and get it every other elementprint(fruits[::-2])  # Output: ['elderberry', 'cherry', 'apple']

5. Multidimensional list

A multidimensional list is a list containing other lists that can be used to represent matrices or other complex data structures.

# Create a 2D listmatrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access the first element of the first lineprint(matrix[0][0])  # Output: 1
# Access all elements in the second lineprint(matrix[1])  # Output: [4, 5, 6]
# Access the second element of all rowsprint([row[1] for row in matrix])  # Output: [2, 5, 8]

6. List analysis

List parsing is a concise way to create new lists, while filtering elements with conditional expressions.

# Create a new list containing strings with length greater than 5 in the original listlong_fruits = [fruit for fruit in fruits if len(fruit) > 5]
print(long_fruits)  # Output: ['banana', 'elderberry']
# Create a new list containing the length of each element in the original listlengths = [len(fruit) for fruit in fruits]
print(lengths)  # Output: [5, 6, 6, 4, 10]

7. Slice assignment

Slices can be used not only to get a part of a list, but also to modify a part of a list.

# Modify the first two elementsfruits[:2] = ['orange', 'grape']
print(fruits)  # Output: ['orange', 'grape', 'cherry', 'date', 'elderberry']
# Insert new elementfruits[2:2] = ['kiwi', 'lemon']
print(fruits)  # Output: ['orange', 'grape', 'kiwi', 'lemon', 'cherry', 'date', 'elderberry']

8. Delete elements

Use slice and del statements to easily delete elements in a list.

# Delete the first two elementsdel fruits[:2]
print(fruits)  # Output: ['kiwi', 'lemon', 'cherry', 'date', 'elderberry']
# Delete the last elementdel fruits[-1]
print(fruits)  # Output: ['kiwi', 'lemon', 'cherry', 'date']

9. Reverse List

Use slices to reverse the list easily.

# Invert the listreversed_fruits = fruits[::-1]
print(reversed_fruits)  # Output: ['date', 'cherry', 'lemon', 'kiwi']

10. Practical cases: Handling student grades

Suppose you have a list of students with their names and grades, you need to complete the following tasks: 1. Find out all students with grades greater than or equal to 90. 2. Arrange all students' grades in descending order. 3. Print each student’s name and grades.

# Student name and grade liststudents = [
    ('Alice', 85),
    ('Bob', 92),
    ('Charlie', 78),
    ('David', 90),
    ('Eve', 88)
]

# 1. Find all students with scores greater than or equal to 90high_scores = [(name, score) for name, score in students if score >= 90]
print(high_scores)  # Output: [('Bob', 92), ('David', 90)]
# 2. Arrange all students' grades in descending ordersorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print(sorted_students)  # Output: [('Bob', 92), ('David', 90), ('Eve', 88), ('Alice', 85), ('Charlie', 78)]
# 3. Print each student’s name and gradesfor name, score in sorted_students:
    print(f"{name}: {score}")

Summarize

This article introduces advanced indexing techniques for Python lists, including basic indexing, slices, negative index slices, step sizes, multi-dimensional lists, list parsing, slice assignment, delete elements, invert lists, etc. With these tips, you can process and manipulate list data more efficiently.

This is the article shared about advanced indexing techniques for lists in Python. For more related advanced indexing content on Python lists, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!