# 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']
print(fruit[2:4])
print(fruit[1:-1])
print(fruit[:3])
last_fruit = fruit[-1:]
print(last_fruit)

['Pears', 'Bananas']
['Oranges', 'Pears']
['Apples', 'Oranges', 'Pears']
['Bananas']


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']
print(fruit)

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

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

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

# 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']
print(fruit)

['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.