List Slicing

list slicing

List slicing

Video Transcript

In this section, we're going to learn about list slicing. Slicing allows us to access individual elements and subsections of a list.
The elements in a list are ordered, and each is given an index number starting from 0 for the first element, and counting up by one. So in the list x = ["a", "b", "c", "d", "e", "f", "g"], the element "a" has index 0, the element "b" has index 1, the element "c" has index 2, and so on. If we want to grab a particular element from a list, all we need to know is its index. Then we can ask for it using square brackets like this:
# printing the letter "c"
x = ["a", "b", "c", "d", "e", "f", "g"]
# c
If we want to get more than one element, we can expand on the notation inside the square brackets to take full advantage of Python slicing. The full syntax is [starting_index:ending_index:step_size].
Python makes a few assumptions based on which parts of the slicing syntax you include:
  • If there are no colons, the single number is used as an index to get a single element
  • The first number before any colons is assumed to be start_index, a number after the first colon is assumed to be end_index, and a number after the second colon is assumed to be step_size
  • The default values, if any are missing, are [0:len(list):1]
Let's see this in action a few times:
x = ["a", "b", "c", "d", "e", "f", "g"]

print(x[1]) # b
print(x[1:]) # ["b", "c", "d", "e", "f", "g"]
print(x[1:4]) # ["b", "c", "d"]
print(x[1::2]) # ["b", "d", "f"]
print(x[1:6:3]) # ["b", "e"]

print(x[:5]) # ["a", "b", "c", "d", "e"]
print(x[:5:2]) # ["a", "c", "e"]

print(x[::2]) # ["a", "c", "e", "g"]
One more thing about slicing is that we can not only count forward with positive numbers, but we can also count backwards using negative numbers. So using index -1 would get us the last element in the list, and having a step_size of -1 would get the list in reverse:
x = ["a", "b", "c", "d", "e", "f", "g"]

print(x[-1]) # g
print(x[:-2]) # ["a", "b", "c", "d", "e"]
print(x[::-1]) # ["g", "f", "e", "d", "c", "b", "a"]
Last section Next section