Flat_Eric dressed as a samurai holding a sword

List Slicing

Absorb what is useful, discard what is not, add what is uniquely your own.

List Slicing

If you remember when we learned about strings and string indexes, we used a technique called slicing with the format [start:stop:step]. We can apply this exact same logic to lists!

Since lists are also ordered collections, we can use slicing to grab a specific "chunk" or sub-section of our data.

List Slicing Example

To understand slicing, you have to look at the Index Positions (the address) of each item in the list. Let's look at a list of colors:

colors = ['red', 'blue', 'green', 'yellow', 'orange', 'purple']

  1. The Basic Slice (Start and Stop)
  2. If we want to grab a specific chunk—for example, 'blue', 'green', and 'yellow'—we look at their positions:

    • Blue is at index 1 (Start).
    • Yellow is at index 3, so we must stop at index 4 (Stop) because Python does not include the stop number.
  3. Using the Step
  4. What if we want to skip items? We use the Step to tell Python how to "jump" through the list. To grab every second color starting from the beginning:

  5. Slicing Shortcuts
  6. You don’t always have to provide all three numbers. If you leave a spot blank, Python fills in the gaps for you:

    • colors[:3] → Starts at the beginning and stops before index 3. (Result: ['red', 'blue', 'green'])
    • colors[2:] → Starts at index 2 and goes to the very end. (Result: ['green', 'yellow', 'orange', 'purple'])

Try It Yourself: The Weekend Slice

Now it’s your turn! Use the days_of_the_week list in the pyBox. Your goal is to use slicing to extract specific days.

  1. Print everyday of the week to the terminal.
  2. Print every-other day of the week to the terminal.
  3. Extract only the weekend days from the list and print them to the terminal.
  4. Print yesterday, today and tomorrow to the terminal.

Mutability

There is a significant difference between strings and lists. If you remember our lesson on immutability, we learned that strings are immutable. While we can access each index in a string to "do something" with it, that action does not change the original string itself.

The only way to change a string is to either:

  1. Save the modification to a new string variable.
  2. Re-assign the modification back to the original variable, which replaces the old string in memory with the new one.

String immutability vs. list mutability

When we try to change an index in a string we get a type error: TypeError: 'str' object does not support item assignment

List mutability

In Python, we can use indexing to select a specific item in a list and either replace it or modify it.

Think of a list like a bookcase. You can remove a book and replace it with a new one; the bookcase is still there, but it now contains a different item. You could also take a book out, "modify" it (like tearing out a page), and put it back. You can even add entirely new books or remove them altogether.

Because lists allow these changes, we call them mutable. This is the opposite of strings, which cannot be changed once they are created.

Memory Referencing

The "Copy" Trap: References vs. Copies In Python, there is an important concept to understand about how lists are stored in memory.

 
# If we have a list of colors and want to change one color
# we can use indexing to select the color and change it:

colors = ['red', 'blue', 'green', 'yellow', 'orange', 'purple']
colors[0] = 'black'
print(colors)
    
 
# Now when we print the list we can see black has replaced red

['black', 'blue', 'green', 'yellow', 'orange', 'purple']
    

The Problem: The "Same List" Trap Let’s look at what happens when you try to create a new list just by using the equals sign (=):

  1. Using the code above try to create a new list named new_colors and assign the new list = to the original list. (new_colors = colors)
  2. Change the color at the first index from black to pink and print new_colors. You should now see ['pink', 'blue', 'green', 'yellow', 'orange', 'purple'] in the terminal.
  3. Now print colors, what do you see in the terminal? How did the original list change if we only changed new_colors? What happen is we assigned new_colors = colors, so we basically said that new_color and colors are the same, so if we change one we change both.
  4. Instead of using new_colors = colors which makes them the same we want to just make the new list equal the contents of the original list. Try new_colors = colors[:], and print both new_colors and colors to the terminal.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: The Odd Slice:

Use slicing to extract only the odd numbers from this list: numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Your goal is to get [1, 3, 5, 7, 9].

Exercise 2: The Reverse Slice:

Take the list: letters = ['A', 'B', 'C', 'D', 'E']. Use a negative step in your slice to reverse the order so the result is ['E', 'D', 'C', 'B', 'A'].

Exercise 3: The Copy Fix:

Look at this logic: original_hero = ['Batman', 'Superman', 'Wonder Woman'] sidekick = original_hero If you change sidekick[0] to 'Robin', the original_hero also changes. Rewrite the second line so that sidekick becomes a completely separate copy of the list.

Exercise 4: The Middle Cut:

Take the list: sandwich = ['Bread', 'Lettuce', 'Tomato', 'Cheese', 'Bread']. Use slicing to grab only the three items in the middle: ['Lettuce', 'Tomato', 'Cheese'].

Exercise 5: Negative Slicing:

Take the list: months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']. Use negative indexing to slice out the last three months: ['Oct', 'Nov', 'Dec'].

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course