About 2594 letters
About 13 minutes
Slicing creates a view of part of a tuple or list. The syntax is as follows:
tuple_or_list[:] # Slice of all elements
tuple_or_list[start:] # Slice from index start to the last element
tuple_or_list[:stop] # Slice from index 0 to index stop (excluding stop)
tuple_or_list[start:stop] # Slice from index start to stop (excluding stop)
tuple_or_list[start:stop:step] # Slice from index start to stop (excluding stop) with step size
Example:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[:])
print(numbers[5:])
print(numbers[:3])
print(numbers[1:4])
print(numbers[2:7:3])
A slice is a reference to the source list, so modifying the slice is equivalent to modifying the source list:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[2:7] = [233] # Replace index 2 to index 7 (excluding 7) with [233]
print(numbers)
Tuples are immutable, so they cannot be modified via slices.
Strings also support slicing:
text:str = "hello world"
print(text[4:7])
Strings are immutable, so they cannot be modified via slices.
If a slice is assigned to a variable, the variable will create a new object based on the slice, rather than referencing the source list:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shadow:list[int] = numbers[2:7] # Assign index 2 to 7 (excluding 7) to variable shadow, creating a new list
shadow[1] = 233 # Modifying shadow does not affect numbers
print(shadow)
print(numbers)
Therefore, slices can be used to simplify list copying:
numbers:list[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shadow:list[int] = numbers[:] # Copy numbers
# shadow:list[int] = list(numbers) # Equivalent
Created in 5/15/2025
Updated in 5/21/2025