Nested List Slicing in Python: Quick Examples

A list is a data structure that stores multiple variables in a single variable. A nested list is a list with the list as elements. In this tutorial, you will learn how to access the elements from the nested list and to perform nested list slicing in Python.

What is the use of Nested List Slicing in Python?

Nested lists, also known as lists of lists, are lists that contain other lists as elements. It provides you with a way to organize and store data in a hierarchical structure. You can access and manipulate the elements within the nested list using slicing.

Examples of Nested List Slicing

Example 1: Accessing Elements in a Nested List

Let’s say below is an example of a nested list.

nested_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]

To access individual elements within this nested list, you will use the square bracket notation. For example, to access element 50, you will use the following syntax.

element = nested_list[1][1]
print(element )

Output

50

Here, nested_list[1] returns the second sublist [40, 50, 60], and nested_list[1][1] returns the element at index 1 within that sublist, which is 50.

Example 2: Slicing a Nested List

You can also use the slicing technique to extract a portion of a nested list. Let’s consider the same nested list as before:

nested_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]

To extract a sublist from the nested list, you can use the slicing notation. For example, to extract the sublist [40, 50, 60], you will use the following syntax.

sublist = nested_list[1:2]
print(sublist )

Output

[[40, 50, 60]]

Here, nested_list[1:2] returns a new list containing the sublist from index 1 (inclusive) to index 2 (exclusive), which is [40, 50, 60].

Example 3: Modifying Elements in a Nested List

Nested list slicing also allows you to modify elements within a nested list. I am using the same nested list as before.

nested_list = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]

To modify an element within this nested list, you will use the assignment operator. For example, to change the element at index 0 in the second sublist from 4 to 10 use the below lines of code.

nested_list[1][0] = 100
print(nested_list )

After executing this line of code, the nested list will be updated as follows.

Output

[[10, 20, 30], [100, 50, 60], [70, 80, 90]]

Conclusion

Slicing the nested list is a powerful technique to access, extract, and modify elements within the list. You can use these features to efficiently work that requires complex data structures. The above are examples you have learned how to access elements, extract sub-lists, etc.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link