You may see some code in Python like list[-1]
, list[:n]
, list[-n:]
, or list[::-1]
. What do they mean? In this article, we will learn more about this technique which is called list slicing.
In simple words, the meaning of those expressions is:
list[-1]
: get the last element of the listlist[:n]
: get the firstn
elements of the listlist[-n:]
: get the lastn
elements of the listlist[::-1]
: reverse the list
Keep reading to understand more how list slicing works.
Table of Contents
What is List Slicing?
In Python, list slicing is a technique to get a subset of a list using indices. The syntax is list[start:end:step]
where:
start
: the index of the first element in the subset (inclusive), default to0
end
: the index of the last element in the subset (exclusive), default tolen(list)
step
: the step size to get elements in the subset, default to1
For example, numbers[1:10:3]
means to get all numbers from index 1
to 10
with a step size of 3
.
Let's make that example more clear.
numbers = [2, 1, 0, 3, 5, 6, 8, 9, 7, 4] print(numbers[1:10:3]) # Output: [1, 5, 9]
We have a list numbers
with 10 elements. So numbers[1:10:3]
are elements at 1
, 4
, and 7
indices, which are 1
, 5
, and 9
, respectively.
What Does list[-1] Mean?
list[-1]
means to get the last element of the list. It is equivalent to list[len(list) - 1]
.
numbers = [2, 1, 0, 3, 5, 6, 8, 9, 7, 4] print(numbers[-1]) # Output: 4
What Does list[:n] Mean?
list[:n]
means to get the first n
elements of the list. It is equivalent to list[0:n]
.
If n
is greater than the length of the list, it will return all elements of the list.
numbers = [2, 1, 0, 3, 5, 6, 8, 9, 7, 4] print(numbers[:3]) # Output: [2, 1, 0] print(numbers[:0]) # Output: [] print(numbers[:100]) # Output: [2, 1, 0, 3, 5, 6, 8, 9, 7, 4]
What Does list[-n:] Mean?
list[-n:]
means to get the last n
elements of the list. It is equivalent to list[len(list) - n:]
.
numbers = [2, 1, 0, 3, 5, 6, 8, 9, 7, 4] print(numbers[-3:]) # Output: [9, 7, 4] print(numbers[-5:]) # Output: [6, 8, 9, 7, 4]
What Does list[::-1] Mean?
list[::-1]
means to reverse the list. It is equivalent to list[len(list) - 1:0:-1]
.
Let's break it down:
len(list) - 1
: the index of the last element of the list0
: the index of the first element of the list-1
: the step size to get elements in the subset
So, in word, it means to go backward from the last element to the first element with a step size of 1
.
numbers = [2, 1, 0, 3, 5, 6, 8, 9, 7, 4] print(numbers[::-1]) # Output: [4, 7, 9, 8, 6, 5, 3, 0, 1, 2]