Workshop 4

List Slicing

We say that list[i] evalues to the ith element of list. list[i:j] makes a new list that contains the elements from i up to but not including j.

In [1]:
fruit = ['Apples', 'Oranges', 'Pears', 'Bananas']
last_fruit = fruit[-1:]
['Pears', 'Bananas']
['Oranges', 'Pears']
['Apples', 'Oranges', 'Pears']

Notice that negative indexing can be used. Notice that a : on either side of the comma gets that end of the list. Notice that even though the last list contains only one element, it is still a list.

List Splicing

We can also assign a list to a slice. This replaces the slice with the new list. The slice you replace and the replacement slice don't have to have the same number of elements. That means you can use splicing to increase or decrease lists.

In [2]:
# if the two list are the same size, it does as expected and just replaces them
fruit[1:3] = ['Navel Oranges', 'Anjou Pears']

# but if you replace with an empty list, it removes items
fruit[2:3] = []

# or you could replace a slice with a longer list
fruit[1:3] = ['beets', 'carrots', 'peppers', 'cabbage']

# or you could replace an empty slice even
fruit[1:1] = ['chocolate']

# notice that assigning a list to a slice of length 1
# is different than assigning a list to a single element
fruit[2] = ['X', 'Y']
['Apples', 'Navel Oranges', 'Anjou Pears', 'Bananas']
['Apples', 'Navel Oranges', 'Bananas']
['Apples', 'beets', 'carrots', 'peppers', 'cabbage']
['Apples', 'chocolate', 'beets', 'carrots', 'peppers', 'cabbage']
['Apples', 'chocolate', ['X', 'Y'], 'carrots', 'peppers', 'cabbage']

That last example, assigned a list into fruit[2]. That's called a nested list and we will talk about them next.