Python Access List Items
You reach individual list items through their index number, and you can grab a whole section at once using slicing.
Indexing from the start
Every item in a list has a position called an index. Python counts positions starting at 0, so the first item is at index 0, the second at index 1, and so on. Put the index in square brackets after the list name to read the value stored there.
Reading by index
colors = ["red", "green", "blue", "yellow"]
print(colors[0])
print(colors[2])colors[0] returns 'red' and colors[2] returns 'blue'. If you ask for an index that does not exist, such as colors[10] here, Python raises an IndexError to warn you that the position is out of range.
Negative indexing
Negative numbers count backwards from the end of the list. This is handy when you care about the last few items but do not know how long the list is. Index -1 always refers to the final item, -2 to the second-to-last, and so on.
Slicing a range
colors = ["red", "green", "blue", "yellow"]
print(colors[-1])
print(colors[1:3])colors[-1] gives 'yellow'. The slice colors[1:3] returns a new list ['green', 'blue'] containing items from index 1 up to, but not including, index 3. The end position in a slice is always excluded.
- Use the 'in' keyword to check for membership: 'blue' in colors returns True.
- A slice always produces a brand-new list and leaves the original untouched.
- Reading an out-of-range index raises IndexError, but slicing out of range simply returns as much as is available.