I recently learned that Python allows assignment to list slices. Instead of simply doing a list element assignment like this:

my_list = [0, 1, 2, 3, 4]
my_list[1] = 9

print(my_list)  # [0, 9, 2, 3, 4]

Python lets you do the same mutation using slice assignment:

my_list = [0, 1, 2, 3, 4]
my_list[1:2] = [9]

print(my_list)  # [0, 9, 2, 3, 4]

It can also be used to replace multiple elements at a time:

my_list = [0, 1, 2, 3, 4]
my_list[2:4] = 9, 8

print(my_list)  # [0, 1, 9, 8, 4]

Or to replace multiple elements on a step interval:

my_list = [0, 1, 2, 3, 4]
my_list[::2] = 9, 8, 7

print(my_list)  # [9, 1, 8, 3, 7]

The slice notation can be confusing, so keep in mind that list element indexes are different from slice indexes. When slicing lists, the start and stop positions refer to the spaces between the elements and not to the elements themselves:

Element indexes count the elements in a list, but slice indexes count the spaces between elements.

And of course, slice assignment can do more than just replace list elements. It can be used for adding or removing a variable number of list elements too!

Adding elements to a list

my_list = [0, 1, 2, 3, 4]
my_list[1:1] = 9, 8, 7, 6

print(my_list)  # [0, 9, 8, 7, 6, 1, 2, 3, 4]

Elements can be replaced and added simultaneously as well:

my_list = [0, 1, 2, 3, 4]
my_list[2:4] = 9, 8, 7, 6

print(my_list)  # [0, 1, 9, 8, 7, 6, 4]
my_list = [0, 1, 2, 3, 4]
my_list[3:] = 9, 8, 7, 6

print(my_list)  # [0, 1, 2, 9, 8, 7, 6]

Removing elements from a list

my_list = [0, 1, 2, 3, 4]
my_list[1:2] = ""

print(my_list)  # [0, 2, 3, 4]
my_list = [0, 1, 2, 3, 4]
my_list[2:4] = ""

print(my_list)  # [0, 1, 4]