Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Slices

3.4 - Slices

In Python, a slice is a portion of a sequence (such as a string, list, or tuple). Slicing allows you to extract specific parts of a sequence using a simple and flexible syntax.

Basic Slicing Syntax

The general syntax for slicing is:

sequence[start:stop:step]
  • start: The index where the slice begins (inclusive).
  • stop: The index where the slice ends (exclusive).
  • step: The interval between elements (optional).

Examples of Slicing

1. Slicing a String

text = "Hello, World!"

print(text[0:5])   # Output: Hello
print(text[:5])    # Output: Hello (start defaults to 0)
print(text[7:])    # Output: World! (stop defaults to the end)
print(text[:])     # Output: Hello, World! (entire string)

2. Slicing a List

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

print(numbers[2:6])   # Output: [2, 3, 4, 5]
print(numbers[:4])    # Output: [0, 1, 2, 3]
print(numbers[5:])    # Output: [5, 6, 7, 8, 9]

3. Using a Step Value

text = "Hello, World!"

print(text[::2])   # Output: Hlo ol!
print(text[1::2])  # Output: el,Wrd
print(text[::-1])  # Output: !dlroW ,olleH (reversing a string)

Exercise: Try It Yourself!

  1. Extract the word "Python" from the string "I love Python programming!" using slicing.
  2. Reverse the string "abcdef" using slicing.
  3. Given the list numbers = [10, 20, 30, 40, 50, 60, 70, 80], use slicing to extract [30, 40, 50].
  4. What will be the output of numbers[::-2] if numbers = [1, 2, 3, 4, 5, 6, 7, 8]?

Try these exercises in your Python environment and test your understanding!