Python List Slicing: Get Part of a List
Slicing: Get Part of a List
Slicing takes a part of a list. Write list[start:stop], and Python gives you a new list with the items from start up to, but not including, stop.
Think of cutting a few slices from a loaf of bread. You choose where the knife starts and where it stops, and you take the piece in between.
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[1:4])['Tue', 'Wed', 'Thu']
| Item | "Mon" | "Tue" | "Wed" | "Thu" | "Fri" |
|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 |
days[1:4] starts at index 1 ("Tue") and stops before index 4, so "Fri" is left out.
The rules
startis included,stopis not.- The number of items you get is
stop - start. Here, 4 - 1 = 3 items. - A slice is always a list, with brackets, even when it holds one item.
An item or a slice?
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[2])
print(days[2:3])
print(days[0:2])Wed ['Wed'] ['Mon', 'Tue']
days[2] with one number gives the item: the string Wed. days[2:3] with a colon gives a list that holds that item.
Common beginner doubt: why is stop left out?
It looks odd at first, but it makes slices fit together neatly. days[0:2] and days[2:5] share the number 2, and together they make the whole list, with no item twice and none missing. And stop - start is always the number of items.
list[start:stop]gives the items from start up to, but not including, stop.