Indexing and slicing
Gets one item, or a range of items, from a string or list by position.
Synopsis
items[index]
items[-1]
items[start:stop]
items[index] = value
Description
Positions start at 0. A negative index counts from the end: -1 is the last item.
A slice [start:stop] takes the items from start up to, but not including, stop. Leave either out to go to the end.
You can change a list item with =, but not a character in a string.
Parameters
| Name | Meaning |
|---|---|
index |
A position, from 0 to len(items) - 1, or negative from the end. |
start, stop |
Where a slice begins and the position it stops before. |
Return value
One item, or a new string or list for a slice.
Example
word = "python"
print(word[0])
print(word[-1])
print(word[0:3])
print(word[2:])
nums = [10, 20, 30]
nums[1] = 25
print(nums)
It prints:
p
n
pyt
thon
[10, 25, 30]
Common mistake
word = "python"
print(word[6])
Python stops with:
IndexError: string index out of range
"python" has 6 letters at positions 0 to 5. The last one is word[5], or word[-1].
See also
Last updated 2 weeks ago