Indexing & slicing, explained simply
Every item in a list has a position number called an index. Python starts counting at 0, so the first item is at index 0, the second at 1, and so on. You ask for an item with square brackets: shelf[0].
Negative indexes count from the end: shelf[-1] is the last item. This saves you from working out how long the list is.
A slice takes a section: shelf[1:3] gives the items at positions 1 and 2, stopping before 3. Strings can be indexed and sliced exactly the same way, one letter at a time.
Example: Take books from the shelf
shelf = ["atlas", "comic", "diary", "poems"]
print(shelf[0])
print(shelf[-1])
print(shelf[1:3])
print("treasure"[0:5])Output
atlas
poems
['comic', 'diary']
treasTry this
- Print the second letter of your name using an index.
- Ask for shelf[10] and read the error. What does it tell you?
- Use shelf[::-1] and work out what the extra part of the slice does.
