Modifying a single element

Let’s learn how to modify a single element within a list. The element to be modified is accessed by passing the element’s index into the [] operator. The new value is assigned on the right hand of the assignment operator.

Suppose there’s a list containing the names of shades of blue called blue_shades and we want to correct one of the spellings from 'saphire' to 'sapphire'. We can do this by executing the following code snippet:

blue_shades = ['navy', 'sky blue', 'saphire', 'powder blue', 'teal', 'turquoise']
blue_shades[2] = 'sapphire'
print(blue_shades)

Modifying multiple elements

When there’s the same number of elements to be added as the specified range, more than one item can also be updated by simply specifying the range. For instance, changing the first two colors to 'denim' and 'aqua', can be done by providing a range from 0 to 2 (exclusive).

blue_shades = ['navy', 'sky blue', 'sapphire', 'powder blue', 'teal', 'turquoise']
blue_shades[0:2] = ['denim', 'aqua']
print(blue_shades)

Different number of elements than the specified range

If the number of elements exceeds the specified range within the indexing [] operator in Python, the language will replace the specified range, incorporate the exceeding elements from the next positions, and adjust the rest accordingly.

blue_shades = ['navy', 'sky blue', 'sapphire', 'powder blue', 'teal', 'turquoise']
blue_shades[0:1] = ['denim', 'aqua']
print(blue_shades)

In the given example, the list blue_shades initially contains various shades of blue. The code then uses the indexing operator to replace elements within a specified range, starting from index 0 (inclusive) to index 1 (exclusive), with the values ‘denim’ and ‘aqua’. In this case, only the element at index 0, representing ‘navy’, is replaced with ‘denim’. ‘aqua’ is added at the next position without affecting the original ‘sky blue’. The elements following ‘denim’ are simply shifted one position forward.

blue_shades = ['navy', 'sky blue', 'sapphire', 'powder blue', 'teal', 'turquoise']
blue_shades[0:4] = ['denim', 'aqua']
print(blue_shades)

On the other hand, when providing a larger range than the elements provided, the replacement covers the complete specified range, and the remaining elements shift accordingly. In the example below, we replace the portion from index 0 (inclusive) to index 4 (exclusive) with ‘denim’ and ‘aqua’, and the last two elements remain unchanged. This reduces the total number of elements.

Reassigning a list

A list can be completely updated by reassigning it with the new values regardless of the previous ones. Let's reassign the list blue_shades with three completely new shades.

blue_shades = ['navy', 'sky blue', 'sapphire', 'powder blue', 'teal', 'turquoise']
blue_shades = ['cobalt', 'azure', 'ice blue']
print(blue_shades)