List indexing in python [Detailed Guide with Examples] - JSON Viewer

List indexing in python [Detailed Guide with Examples]

What is list indexing in python?

In Python, list indexing is a concept that allows accessing elements of a list with their index or sequence, or position number wrapped inside the square brackets[].

Python has two types of indexing:

  • Positive Indexing
  • Negative Indexing

Positive indexing

Positive indexing is the way of accessing elements from the list from left to right. It will start from index 0 to the length of the list minus 1.

Accessing the first element

colours = ["red", "blue", "orange"]
print(colours[0])
# Output: "red"

In the above example, there is a list named colours and it has 3 elements inside “red”, “blue” and “orange”.

In list indexing, the index number starts from 0. So, the first element in the list will have the index number 0, the second element will have the index number 2, and so on.

Accessing the last element

colours = ["red", "blue", "orange", "green", "yellow"]
last_element = colours[len(colours)-1]
print(last_element)
#output = yellow

In this example the length of the list is 5. So len(colours) gives 5. Then, colours[len(colours)-1] accesses the last element of the list, which is “yellow”.

Accessing the Middle element

colours = ["red", "blue", "green", "yellow", "purple"]
print(colours[int(len(colours)/2)])
# Output: "green"

In this example, the length of the colours list is 5, so int(len(colours)/2) evaluates to 2. Thus, colours[2] is “green”, which is the value that will be printed.

Accessing Multiple elements

Rather than accessing each elements from a list, you can also access multiple elements by giving a specific range

animals = ["cat", "dog", "cow", "elephant", "goat"]
print(animals[1:3])
# Output: ['dog', 'cow']

In this example, the range 1:3 is used to access the second and third elements in the list, which are “dog” and “cow”. The slicing notation [start:end] is used to extract elements from start to end-1.

Negative indexing

Negative indexing allows access to elements of the list from right to left. The indexing starts from -1 to the negative of the length of the list.

Access the First element

colours = ["red", "blue", "green", "yellow", "purple"]
print(colours[-len(colours)])
# Output: "red"

In this example, the length of the colours list is 5, so -len(colours) is -5. Thus, colours[-5] is “red”, which is the value that will be printed.

This demonstrates that negative indexing can be used to access elements of a list from the end, where -1 refers to the last element, -2 refers to the second to last element, and so on.

Accessing the Last element

colours = ["red", "blue", "orange"]
print(colours[-1])
# Output: "orange"

In this example, the index -1 is used to access the last element in the list, which is “orange”.

Accessing the Middle element

colours = ["red", "blue", "green", "yellow", "purple"]
print(colours[-int(len(colours)/2)])
# Output: "yellow"

In this example, the list names colours have a length 5, so int(len(colours/2) gives 2.

-int(len(colours/2) is -2. So, colours[-2] is “yellow”, it shows that negative indexing can be used to access elements of a list from the end, where -1 refers to the last element, -2 refers to the 2nd last element and so on.

Access Multiple elements

animals = ["cat", "dog", "cow", "elephant", "goat"]
print(animals[-4:-1])
# Output: ['dog', 'cow', 'elephant']

we can also access a specific range of elements by specifying both the start and end indices. From the above example, to access the second to the fourth elements of the list animals, we can use the negative indexes as animals[-4:-1]

Update the elements in the list using indexing:

Finally, list indexing can also be used to update elements inside a list.

For example:

names = ["Tom","Rose","Jacob"]
names[1] = "Bob"
print(names) # Output: ['Tom', 'Bob', 'Jacob']

In this example, index 1 is used to access the second element in the list, which was originally “Rose”. The value of that element is then updated to “Bob”.

We can go with other example,

names = ["Tom","Rose","Jacob"]
names[0] = "bella"
print(names) # Output: ['bella', 'Bob', 'Jacob'] 

In this example, index 0 is used to access the 1st element in the list, which was originally “Tom”. The value of that element is then updated to “bella”.

Remove the elements from the list using indexing:

Removing elements from a list:

names = ["Tom","Rose","Jacob"]
names.pop(2)
print(names) # Output: ['Tom', 'Rose']

The pop method is then used to remove the element with its index.

In this example it is taking index 2 which will remove the element “Jacob.

Finally, the updated list is printed and it returns [‘Tom’, ‘Rose’] where the element at index 2 has been removed.

We can try with one more example,

names = ["Tom","Rose","Jacob"]
names.pop(0)
print(names) # Output: ['Rose',”Jacob]

In this example the list has 3 elements. Here we are going to remove the 1st element, so index 0 will be used. Finally the output will be [ “Rose”, “Jacob” ] where the element at index 0 has been removed.

Do try it out by yourselves with some examples.

Handling List Indexing Errors in Python

There are a few errors that you might encounter when using list indexing in Python:

  1. IndexError: This error occurs when you try to access an index outside of the boundary of the list.

For example:

names = ["Alice", "Alan", "Ben"]
print(names[3])
# Output: IndexError: list index out of range

In this list there are only 3 elements, So the maximum indexing is 2 and here it is trying to access an index with 3 that is out of the boundary of the list so it will show IndexError.

2. TypeError: This error occurs when you try to access the list using non-integer values.

For example:

names = ["Alice", "Alan", "Ben"]
print(names["Alan"]) # Output: TypeError:
# list indices must be integers or slices, not strOutput

In this example, the index “Alan” is not an integer, so a TypeError is raised.

3. ValueError: This error occurs when you try to use an index that is out of the valid range of indices for a list.

For example:

names = ["Alice", "Alan", "Ben"]
print(names["-4"])
# Output: ValueError: list index out of rang

In this example, the index -4 is outside the valid range of negative indices for the list names.

List indexing is an important feature in python programming for accessing the elements in the list. If you are a python programmer it is very important to understand list indexing.