Array slicing in Python
PythonArray slicing in Python allows you to extract a portion of a list, string, or other sequence types. Here are some examples of array slicing in Python.
1. Basic Slicing
# Example list
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from index 2 to 5 (exclusive)
slice1 = arr[2:5]
print(slice1) # Output: [2, 3, 4]
# Slice from the beginning to index 4 (exclusive)
slice2 = arr[:4]
print(slice2) # Output: [0, 1, 2, 3]
# Slice from index 6 to the end
slice3 = arr[6:]
print(slice3) # Output: [6, 7, 8, 9]
# Slice the entire list
slice4 = arr[:]
print(slice4) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Negative Indexing
# Slice from index -4 to -1 (exclusive)
slice5 = arr[-4:-1]
print(slice5) # Output: [6, 7, 8]
# Slice from index -3 to the end
slice6 = arr[-3:]
print(slice6) # Output: [7, 8, 9]
3. Step in Slicing
# Slice from index 1 to 8 with a step of 2
slice7 = arr[1:8:2]
print(slice7) # Output: [1, 3, 5, 7]
# Slice the entire list with a step of 3
slice8 = arr[::3]
print(slice8) # Output: [0, 3, 6, 9]
# Reverse the list using slicing
slice9 = arr[::-1]
print(slice9) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
4. Slicing with Strings
# Example string
s = "Hello, World!"
# Slice from index 7 to 12 (exclusive)
slice10 = s[7:12]
print(slice10) # Output: "World"
# Slice from the beginning to index 5 (exclusive)
slice11 = s[:5]
print(slice11) # Output: "Hello"
# Slice from index -6 to the end
slice12 = s[-6:]
print(slice12) # Output: "World!"
# Reverse the string
slice13 = s[::-1]
print(slice13) # Output: "!dlroW ,olleH"
5. Slicing with Multi-dimensional Arrays (e.g., NumPy)
import numpy as np
# Example 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Slice the first two rows and the last two columns
slice14 = arr_2d[:2, 1:]
print(slice14)
# Output:
# [[2 3]
# [5 6]]
# Slice the entire second column
slice15 = arr_2d[:, 1]
print(slice15) # Output: [2 5 8]
6. Slicing with Tuples
# Example tuple
t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# Slice from index 2 to 6 (exclusive)
slice16 = t[2:6]
print(slice16) # Output: (2, 3, 4, 5)
These examples demonstrate the flexibility of slicing in Python, which can be applied to various sequence types like lists, strings, tuples, and even multi-dimensional arrays.