How does Python slicing differ from indexing?

QuestionsQuestions8 SkillsProDec, 21 2025
0124

That is an excellent question! While they look similar, the main difference is between picking one single item versus picking a group of items.

Here is the breakdown:

1. Indexing (The "Sniper")

Indexing is used to get one specific character at a specific position.

  • Syntax: string[index]
  • Result: A single character.
  • Crash Risk: If you ask for an index that doesn't exist (like [100]), Python will crash with an IndexError.
name = "Python"
print(name[0])  # Output: 'P' (Just one letter)

2. Slicing (The "Knife")

Slicing is used to get a substring (a chunk or a range) from the original string.

  • Syntax: string[start:stop]
  • Note: The start is included, but the stop is excluded.
  • Result: A new string (it could be empty, one letter, or the whole thing).
  • Safe: If your slice range is too big (like [0:100]), Python won't crash; it just stops at the end of the string.
name = "Python"
# Start at index 0, stop BEFORE index 2
print(name[0:2]) # Output: 'Py'

Comparison at a Glance

Feature Indexing Slicing
Goal Get one character Get a range of characters
Syntax [n] [start:stop:step]
Output Type Character String
Out of Range Causes an Error Returns what it can (No error)

Pro Tip: The "Step"

Slicing has a secret third part called the step: [start:stop:step].
If you want every second letter of your name, you can do:

print(full_name[::2]) 

Try this in your terminal:
Try to grab just your first name from your full_name variable using slicing! (e.g., full_name[0:8])

0 Comments

no data
Be the first to share your comment!