Python Lists Explained: Ordering, Indexing, Negative Indexing and len()

Lists Are Ordered

A list maintains the order of its objects.

Consider:

numbers = [30, 10, 50, 20, 40]
print(numbers)

Output:

[30, 10, 50, 20, 40]

Python does not automatically arrange these numbers in numerical order.

The order in which we place the objects is retained.

So:

[30, 10, 50, 20, 40]

is different from:

[10, 20, 30, 40, 50]
Key Point: A Python list preserves the order in which its objects are placed. It does not automatically sort the objects.

Accessing Objects in a List

A very important property of a Python list is that we can access individual objects using their index.

Consider:

numbers = [10, 20, 30, 40, 50]

The positions are:

Object: 10 20 30 40 50
Index: 0 1 2 3 4
Important: Python starts indexing from 0, not 1.

Therefore:

numbers[0]

means the first object.

numbers[1]

means the second object.

numbers[2]

means the third object.

Key Point: A Python list starts its indexing from 0. Therefore, index 0 refers to the first object, index 1 refers to the second object, and so on.

Example: Accessing Individual Objects

numbers = [10, 20, 30, 40, 50]
print(numbers[0])
print(numbers[1])
print(numbers[2])

Output:

10
20
30

We can also access the last two objects:

print(numbers[3])
print(numbers[4])

Output:

40
50
Key Point: The index determines which object is accessed from the list.

Negative Indexing

Python also allows us to access objects from the end of a list using negative indexes.

For example:

numbers = [10, 20, 30, 40, 50]

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:

print(numbers[-1])

Output:

50

And

print(numbers[-2])

Output:

40
Remember: Negative indexing is useful when we want to access objects from the end of a list.
Quick Reference:
-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:

numbers = [10, 20, 30, 40, 50]
print(len(numbers))

Output:

5

Therefore, the list contains five objects.

Another example:

names = [“Ram”, “John”, “Ali”]
print(len(names))

Output:

3
Key Point: The len() function returns the number of objects present in a list.
Remember: If a list contains 5 objects, then len(list) returns 5.

Gopal Krishna

Hey Engineers, welcome to the award-winning blog,Engineers Tutor. I'm Gopal Krishna. a professional engineer & blogger from Andhra Pradesh, India. Notes and Video Materials for Engineering in Electronics, Communications and Computer Science subjects are added. "A blog to support Electronics, Electrical communication and computer students".

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »