About 2594 letters

About 13 minutes

#Python's slice operations

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
array array array[3:7] array[3:7] array->array[3:7] values 0 1 2 3 4 5 6 7 8 9 slice 3 4 5 6 values:f3->slice:f3 start values:f6->slice:f6 end-1

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])

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Modifying the Source List

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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#String Slicing

Strings also support slicing:

text:str = "hello world"
print(text[4:7])

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Slice Copying

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)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

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

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025