Python Slicing


Python Slicing


What is Slicing in Python?

Slicing is used to extract a portion (or subset) of a list, string, or tuple using a defined start, stop, and optional step.

General Syntax:

sequence[start:stop:step]

Key Parameters:

  • start: Index to begin the slice (inclusive)
  • stop: Index to end the slice (exclusive)
  • step (optional): Gap between each element

1. Python List Slicing

my_list = [10, 20, 30, 40, 50, 60]
print(my_list[1:4])  # from index 1 to 3

Output:

[20, 30, 40]


2. Slicing With Step

print(my_list[::2])  # Every second element

Output:

[10, 30, 50]


3. Negative Indexing in Slicing

Python allows negative indexes, where -1 refers to the last item.

print(my_list[-4:-1])

Output:

[30, 40, 50]


4. Reverse a List Using Slicing

print(my_list[::-1])  # Reverses the list

Output:

[60, 50, 40, 30, 20, 10]


5. Python String Slicing

text = "PythonSlicing"
print(text[0:6])   # Extract 'Python'
print(text[6:])    # Extract 'Slicing'

Output:

Python
Slicing


6. Slice Tuples

Tuples are immutable but support slicing like lists.

t = (1, 2, 3, 4, 5)
print(t[1:4])

Output:

(2, 3, 4)


7. Using slice() Function

Python provides a built-in slice() constructor.

s = slice(1, 5, 2)
print(my_list[s])

Output:

[20, 40]


Advanced Example: Slice with Conditions

# Get even numbers from a list
nums = [1, 2, 3, 4, 5, 6, 7, 8]
even = nums[1::2]  # Assuming even numbers at even indices
print(even)

Output:

[2, 4, 6, 8]