fbpx

Slicing Lists

Creating a Sublist from a List

We just learned how to create and access individual elements within a list, but we are able to extract a sublist from a given list by “slicing” it. In order to do this, we can specify the starting index (inclusive) and ending index (exclusive) of the values we want to slice. For instance, if I wanted to just extract Luke and Leia from our list of students, we can do the following:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

skywalkers = students[0:2]
print(skywalkers) # just prints Luke and Leia
				
			

In the above code, we use the colon (:) within the hard brackets to separate the beginning and ending index of the values we want to slice. Because the beginning index is inclusive (0) and the ending index is exclusive (2), we only extract the values at index 0 and 1. 

We are also able to slice lists without specifying either a beginning or ending index. In these cases, the list will be sliced up to or after the index that is specified. For example:

				
					animals = ["Cat", "Dog", "Bird", "Fish", "Cow", "Pig", "Monkey"]

print(animals[2:5]) # Bird, Fish, Cow
print(animals[4:]) # Cow, Pig, Monkey (no end index specified)
print(animals[:3]) # Cat, Dog, Bird (no begin index specified)
				
			

We could use these slicing functions to create a new array, for example, that is the same as another array but without one of the values. Notice how we use them in the example below to remove a given animal from the list:

				
					animals = ["Cat", "Dog", "Bird", "Fish", "Cow", "Pig", "Monkey"]

# say we want to remove "bird":
indexToRemove = 2

# combine all elements before bird with all elements after bird:
animals2 = animals[:indexToRemove] + animals[indexToRemove+1:]

# prints the new list without "bird" in it:
print(animals2) 
				
			

Try changing the indexToRemove variable in the above example to see how this allows to remove any element.

Replit Practice

Loading...