Home » Learn Python » Containers » List Slicing

List Slicing

You can retrieve ranges of values (“slices”) from a list using a start:end syntax. All items will be included in the list that’s returned, from the start index up to (but not including) the end index.

If a third argument is used, it specifies a step size.

numbers = [x for x in range(10)]
print(numbers)

print(numbers[2:4])
print(numbers[2:8:2])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3]
[2, 4, 6]

Default Slice Values

All three of these slice indices are optional. The first value defaults to zero. The second defaults to the end of the list. The third (step size) defaults to 1.

This means the following are all perfectly valid slice indices.

print(numbers)
print(numbers[:])
print(numbers[::2])
print(numbers[:5:])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[0, 1, 2, 3, 4]

Leave a Reply

Blog at WordPress.com.

%d