• What a list slicing is
  • How to use the list slicing
  • How to handle nested lists

You have grasped the concept of lists on Day 3. Today, we are going to go deeper into the lists. We will cover the list slicing and nested lists.

1 List Slicing

You can access multiple elements at once using slicing. List slicing in “Python” language refers to a technique used to extract a subset of elements from a list. It allows you to create a new list by specifying a range of indices or positions within the original list. The general syntax for list slicing is list[start:stop:step] (Tip 1).

TIPS: List Slicing

list[start:stop:step]
  • start is the index of the first element you want to include in the slice (inclusive).
  • stop is the index of the first element you want to exclude from the slice (exclusive). In other words, the element before this index will be included.
  • step (optional) is the increment used to determine the elements to include in the slice.

In the example below, we are extracting all the elements ranging from index 1 to index 3. Remember, the index starts with 0.

numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4]  # Retrieves elements at index 1, 2, and 3
print(subset)
[2, 3, 4]

List slicing has different ways of extracting elements:

numbers = [1, 2, 3, 4, 5]
print(numbers[::])  # Retrieve all elements without specifying anything
print(numbers[::2])  # Only specify step, retrieving elements at index 0, 2, 4
print(numbers[::-1])  # Retrieve all elements in the inverse order
[1, 2, 3, 4, 5]
[1, 3, 5]
[5, 4, 3, 2, 1]

2 Nested Lists

You can also create a nested list:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In this nested list, the elements are stored in rows and columns (Table 1).

Table 1: Structure of a Nested List
  Column 0 Column 1 Column 2
Row 0 1 2 3
Row 1 4 5 6
Row 2 7 8 9

The element at Row 0 and Column 0 can be accessed by:

print(nested_list[0][0])  # Row 0, Column 0
1

The first 0 specifies the first row, and the second 0 returns the first column. You will be able to understand the way to access the elements in the nested list by checking these examples:

print(nested_list[0][1])  # Row 0, Column 1
print(nested_list[1][2])  # Row 1, Column 2
print(nested_list[2][2])  # Row 2, Column 2
2
6
9

Also, you can access each row by:

print(nested_list[0])  # Row 0
print(nested_list[1])  # Row 1
print(nested_list[2])  # Row 2
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Accessing each column is not so easy in nested list, and I don’t explain it here. However, for those keen on understanding new things, I paste the code (The code uses a list comprehension):

print([row[0] for row in nested_list])  # Column 0
[1, 4, 7]

3 Exercises