Some text some message..
Back 🧠 What is Slicing in Python? 23 Jun, 2025

Slicing is a way to extract a portion (subsequence) of a sequence like:

  • list

  • string

  • tuple

It allows you to access multiple elements using a range of indexes.


🔹 Syntax of Slicing

sequence[start:stop:step]
Part Meaning
start Index to begin slice (inclusive)
stop Index to end slice (exclusive)
step Interval between elements (default is 1)

✅ If any of the parameters are omitted, defaults are:

  • start = 0

  • stop = length of sequence

  • step = 1


🧪 Examples

➤ On Lists

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

print(my_list[1:4])     # Output: [20, 30, 40]
print(my_list[:3])      # Output: [10, 20, 30]
print(my_list[3:])      # Output: [40, 50, 60]
print(my_list[::2])     # Output: [10, 30, 50]

➤ On Strings

text = "Python"

print(text[0:3])    # Output: Pyt
print(text[::-1])   # Output: nohtyP (Reversed string)

➤ On Tuples

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

🔁 Negative Indexing in Slicing

Python supports negative indices, which count from the end:

my_list = [10, 20, 30, 40, 50]

print(my_list[-3:-1])   # Output: [30, 40]
print(my_list[::-1])    # Output: [50, 40, 30, 20, 10]

📌 Use Cases of Slicing

Use Case Example Code Result
First 3 elements lst[:3] [10, 20, 30]
Last 3 elements lst[-3:] [40, 50, 60]
Reverse list lst[::-1] [60, 50, 40, 30, 20, 10]
Every 2nd element lst[::2] [10, 30, 50]

🔍 Slicing with Step

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

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

⚠️ Out of Range in Slicing

No error is raised when start or stop go out of range.

lst = [1, 2, 3]

print(lst[1:10])   # Output: [2, 3]
print(lst[5:])     # Output: []

🧩 Slice Object (Advanced)

You can create a reusable slice object:

s = slice(1, 5, 2)
print([10, 20, 30, 40, 50, 60][s])  # Output: [20, 40]