Learn
Working with Lists in Python
Slicing Lists

Suppose we have a list of letters:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

Suppose we want to select from b through f.

We can do this using the following syntax: letters[start:end], where:

  • start is the index of the first element that we want to include in our selection. In this case, we want to start at b, which has index 1.
  • end is the index of one more than the last index that we want to include. The last element we want is f, which has index 5, so end needs to be 6.
    sublist = letters[1:6] print(sublist)
    This example would yield:
    ['b', 'c', 'd', 'e', 'f']
    Notice that the element at index 6 (which is g) is not included in our selection.

Creating a selection from a list is called slicing.

Instructions

1.

Use print to examine the variable beginning.

How many elements does it contain?

2.

Modify beginning, so that it selects the first 4 elements of suitcase.

3.

Create a new list called middle that contains the middle two items from suitcase.

Folder Icon

Sign up to start coding

Already have an account?