Range Slicing and Membership in Python
Core idea
A range represents a sequence of integers using start, stop and step rather than storing all of its items. Slicing a range returns another range. Slice indices refer to positions in the original sequence, not the values of those positions. Membership with in tests whether a value occurs in that sequence.
numbers = range(2, 14, 2)part = numbers[1::2]print(list(part))print(part.start, part.stop, part.step)The slice selects positions 1, 3 and 5; list() is used only to display the small result.
Check a ticket number
tickets = range(10, 21, 2)print(14 in tickets)print(15 in tickets)print(21 in tickets)A number must fit both the bounds and step; stop itself is excluded.
Reverse a descending range
numbers = range(9, 0, -3)print(list(numbers[::-1]))print(list(numbers[8:]))A negative slice step reverses the order; an out-of-range slice may be empty.
Common mistake
Being between start and stop does not guarantee membership. Also, a sliced range may have a stop value different from the original without changing the selected items.
Practice
Create range(0, 30, 3), select positions 2 through 5 with a slice and test whether 12 and 15 occur.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Range slicing and membership
Check your understanding of range slicing and membership.
What is printed?
print(list(range(2, 10, 2)[1::2]))What is printed?
print(5 in range(2, 10, 2))What is printed?
print(list(range(6, 0, -2)[::-1]))What type does slicing a range return?