Slicing

Slicing

A slice copies part of a list. It is written with a colon between two indexes: list[start:stop]. The element at start is included; the element at stop is not:

results = ["Ada", "Grace", "Alan", "Edsger", "Barbara"]
print(results[1:3])

Output:

['Grace', 'Alan']

Indexes 1 and 2 — not 3. The slice [1:3] contains stop - start = 2 elements.

Leaving out start means "from the beginning"; leaving out stop means "to the end":

print(results[:2])
print(results[2:])

Output:

['Ada', 'Grace']
['Alan', 'Edsger', 'Barbara']

Negative indexes work in slices: results[-2:] is the last two elements. A slice is a new list — changing it does not change the original.

Exercise

  1. Define a function named podium with one parameter, results (a list of names in finishing order). It returns the first three.
  2. Define a function named eliminated with one parameter, results. It returns everything except the first three.

podium(["A", "B", "C", "D", "E"]) returns ["A", "B", "C"].

Run your code to see the output, then press Submit.

Tests

import unittest


class TestSlicing(unittest.TestCase):
    def test_podium_is_the_first_three(self):
        self.assertEqual(podium(["A", "B", "C", "D", "E"]), ["A", "B", "C"])

    def test_eliminated_is_the_rest(self):
        self.assertEqual(eliminated(["A", "B", "C", "D", "E"]), ["D", "E"])

    def test_podium_does_not_change_the_original(self):
        race = ["A", "B", "C", "D"]
        podium(race)
        self.assertEqual(race, ["A", "B", "C", "D"])

    def test_eliminated_is_empty_for_exactly_three(self):
        self.assertEqual(eliminated(["A", "B", "C"]), [])
def podium(results):
    return results[:3]


def eliminated(results):
    return results[3:]


race = ["Ada", "Grace", "Alan", "Edsger", "Barbara"]
print(podium(race))
print(eliminated(race))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.