Modifying Slices in Python Lists
In addition to accessing elements using slicing, you can also modify the contents of a list by assigning new values to a slice.
Assigning Values to a Slice
To assign new values to a slice, you can use the same syntax as accessing a slice, but instead of just reading the values, you assign new values to the slice.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list[2:6] = ['a', 'b', 'c', 'd']
print(my_list) ## Output: [1, 2, 'a', 'b', 'c', 'd', 7, 8, 9, 10]
In this example, the slice my_list[2:6]
is replaced with the new values ['a', 'b', 'c', 'd']
.
Modifying Slice Length
You can also modify the length of a slice by assigning a different number of elements to it.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list[2:6] = ['a', 'b', 'c']
print(my_list) ## Output: [1, 2, 'a', 'b', 'c', 6, 7, 8, 9, 10]
In this example, the slice my_list[2:6]
is replaced with a shorter list of three elements, effectively removing two elements from the original list.
Inserting Elements Using Slicing
You can also use slicing to insert new elements into a list by assigning an iterable (such as a list) to a slice with a length of 0.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list[2:2] = ['a', 'b', 'c']
print(my_list) ## Output: [1, 2, 'a', 'b', 'c', 3, 4, 5, 6, 7, 8, 9, 10]
In this example, the slice my_list[2:2]
has a length of 0, so the new elements ['a', 'b', 'c']
are inserted at index 2.
By understanding how to modify slices in Python lists, you can perform a wide range of list manipulation tasks, making your code more efficient and flexible.