Python Lists Explained: Ordering, Indexing, Negative Indexing and len()
Lists Are Ordered
A list maintains the order of its objects.
Consider:
Output:
Python does not automatically arrange these numbers in numerical order.
The order in which we place the objects is retained.
So:
is different from:
Accessing Objects in a List
A very important property of a Python list is that we can access individual objects using their index.
Consider:
The positions are:
| Object: | 10 | 20 | 30 | 40 | 50 |
| Index: | 0 | 1 | 2 | 3 | 4 |
Therefore:
means the first object.
means the second object.
means the third object.
Example: Accessing Individual Objects
Output:
20
30
We can also access the last two objects:
Output:
50
Negative Indexing
Python also allows us to access objects from the end of a list using negative indexes.
For example:
The indexes can be viewed as:
| Object: | 10 | 20 | 30 | 40 | 50 |
| Positive: | 0 | 1 | 2 | 3 | 4 |
| Negative: | -5 | -4 | -3 | -2 | -1 |
Therefore:
Output:
And
Output:
-1 → Last object -2 → Second-last object -3 → Third-last object
Finding the Number of Objects in a List
Python provides the len() function to find the number of objects in a list.
Example:
Output:
Therefore, the list contains five objects.
Another example:
Output: