Home › Learn › Python › Lists

Slicing

Lesson 18 of 40. Take part of a list or string with start:stop:step.

A slice items[start:stop] is a new list with the items from start up to but not including stop. Leave out start to begin at the front, leave out stop to run to the end: items[:3] is the first three, items[3:] everything after them, items[-2:] the last two. A third number is the step: items[::2] takes every other item, and items[::-1] is the whole thing reversed.

Slices never raise errors for going past the end; you just get fewer items. They work on strings exactly the same way, and they always return a copy, so the original is untouched.

nums = [10, 20, 30, 40, 50]
print(nums[1:3])    # [20, 30]
print(nums[-2:])    # [40, 50]
print(nums[::-1])   # [50, 40, 30, 20, 10]
print("python"[2:4])  # th

Your task

Using letters from the starter, make first_three, last_two, every_other (a, c, e, g), and backwards (the whole list reversed).

Hint 1

letters[:3] and letters[-2:]

Hint 2

A step of 2 takes every other; a step of -1 reverses.

Show the solution
letters = list("abcdefg")

first_three = letters[:3]
last_two = letters[-2:]
every_other = letters[::2]
backwards = letters[::-1]

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.