Slices and combination

Lesson 35 of 54 · Python Foundations

A slice selects a range of positions and produces a new list. Its general form is items[start:stop:step]: start is included, stop is excluded, and step controls the direction and spacing.

letters = ["a", "b", "c", "d", "e"]
print(letters[1:4])
print(letters[:3], letters[3:])
print(letters[::2], letters[1::2])
print(letters[-3:], letters[::-1])
['b', 'c', 'd']
['a', 'b', 'c'] ['d', 'e']
['a', 'c', 'e'] ['b', 'd']
['c', 'd', 'e'] ['e', 'd', 'c', 'b', 'a']

Omitted endpoints use the appropriate edge for the step direction. The step cannot be zero. A slice whose boundaries extend past the list is clipped rather than raising the IndexError that a single invalid index would. Like [:], slices are shallow copies.

The + operator joins lists in order and produces another list; it does not change either input.

morning = ["tea", "bread"]
evening = ["soup"]
menu = morning + evening
print(menu)
print(morning)
['tea', 'bread', 'soup']
['tea', 'bread']

[::-1] reverses into a new list. By contrast, items.reverse() changes the original list in place and returns None.