截取列表

列表和集合 / 列表

numbers = [2, 3, 5, 7, 11]

first2 = numbers[:2]
# first2 is [2, 3]
last3 = numbers[2:]
# last3 is [5, 7, 11]

# Negative start counts from the end
last2 = numbers[-2:]
# last2 is [7, 11]

# Start is included, end is not
middle = numbers[1:4]
# middle is [3, 5, 7]

# A slice is a copy, not a view
numbers[2] = 50
# numbers is [2, 3, 50, 7, 11], last3 stays [5, 7, 11]

print(f"{first2 = }")
print(f"{last3 = }")
print(f"{last2 = }")
print(f"{middle = }")
print(f"{numbers = }")