Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to index a list in Python

Understanding Lists in Python

In Python, a list is a type of data structure that is mutable, or changeable, and can contain elements of any type. Think of it like a shopping list where you can add, remove, or change items. A list in Python is similar, but instead of groceries, it contains variables or values.

Here is an example of a list in Python:

fruits = ['apple', 'banana', 'cherry']

In this case, fruits is a list that contains three elements, each represented by a string.

Indexing in Python

In Python, indexing is a way to access particular elements in a list. It's like saying, "I want the third item on my shopping list". In Python, you would use the index number to get that item.

However, Python starts counting from 0, not 1. This means the first item in a list is at index 0, the second is at index 1, and so on.

Here's how you can access elements in a list using indexing:

fruits = ['apple', 'banana', 'cherry']
print(fruits[0])  # Output: apple
print(fruits[1])  # Output: banana
print(fruits[2])  # Output: cherry

Negative Indexing

Python also supports negative indexing. It's like reading your shopping list from the bottom up. In negative indexing, -1 refers to the last item, -2 refers to the second last item, and so on.

Here's how you can use negative indexing:

fruits = ['apple', 'banana', 'cherry']
print(fruits[-1])  # Output: cherry
print(fruits[-2])  # Output: banana
print(fruits[-3])  # Output: apple

Indexing Out of Range

What happens if you try to access an index that doesn't exist? Python will raise an IndexError exception. It's like trying to buy an item that's not on your shopping list.

Here's an example:

fruits = ['apple', 'banana', 'cherry']
print(fruits[3])  # Output: IndexError: list index out of range

Indexing to Modify List Elements

Indexing isn't just for accessing elements. You can use it to modify elements in a list too. It's like crossing off an item from your shopping list and adding a new one.

Here's how you can do it:

fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'blueberry'
print(fruits)  # Output: ['apple', 'blueberry', 'cherry']

In this example, the element at index 1 (banana) is replaced with blueberry.


Indexing in Python might seem a little tricky at first, especially if you're not used to counting from 0. But once you get the hang of it, it's a powerful tool that gives you precise control over your data. It's like being able to pick out any item from your shopping list, change it, or even check if it's on the list to begin with. Just remember that Python is like a very obedient shopping assistant: it will do exactly what you ask, so make sure you're asking for something that's actually on the list! Happy coding!