# Slicing in Python

Example 1: Slicing a List

# Slicing a list

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get elements from index 2 to 5 (exclusive)

subset = numbers[2:5]

print(subset)  # Output: [2, 3, 4]

#clcoding.com

[2, 3, 4]

Example 2: Omitting Start and End Indices

# Omitting start and end indices

subset = numbers[:7]  # From the beginning to index 6

print(subset)  # Output: [0, 1, 2, 3, 4, 5, 6]

subset = numbers[3:]  # From index 3 to the end

print(subset)  # Output: [3, 4, 5, 6, 7, 8, 9]

#clcoding.com

[0, 1, 2, 3, 4, 5, 6]

[3, 4, 5, 6, 7, 8, 9]

Example 3: Using Negative Indices

# Using negative indices

subset = numbers[-4:-1]

print(subset)

#clcoding.com

[6, 7, 8]

Example 4: Slicing a String

# Slicing a string

text = "Hello, Python!"

# Get the substring "Python"

substring = text[7:13]

print(substring)  # Output: Python

#clcoding.com

Python

Example 5: Step in Slicing

# Step in slicing

even_numbers = numbers[2:10:2]

print(even_numbers)

#clcoding.com

[2, 4, 6, 8]

Example 6: Slicing with Stride

# Slicing with stride

reverse_numbers = numbers[::-1]

print(reverse_numbers)

#clcoding.com

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Example 7: Slicing a Tuple

# Slicing a tuple

my_tuple = (1, 2, 3, 4, 5)

# Get a sub-tuple from index 1 to 3

subset_tuple = my_tuple[1:4]

print(subset_tuple)  # Output: (2, 3, 4)

#clcoding.com

(2, 3, 4)

Example 8: Modifying a List with Slicing

# Modifying a list with slicing

letters = ['a', 'b', 'c', 'd', 'e']

# Replace elements from index 1 to 3

letters[1:4] = ['x', 'y', 'z']

print(letters)

#clcoding.com

['a', 'x', 'y', 'z', 'e']