Sobes.tech
Junior

What are slices used for in Python?

sobes.tech AI

Answer from AI

Slices in Python are used to obtain a subset or a part of a sequence (string, list, tuple).

Main uses of slices:

  • Getting elements from a specific range of indices.
  • Copying sequences.
  • Reversing sequences.
  • Skipping elements with a certain step.

Slice syntax: sequence[start:stop:step], where:

  • start (optional) - starting index (inclusive). Default is 0.
  • stop (optional) - ending index (exclusive). Default is the length of the sequence.
  • step (optional) - step. Default is 1.

Examples:

string = "Hello, World!"
# Getting a substring from index 0 to 5 (excluding)
substring1 = string[0:5]  # "Hello"

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Getting a sublist from index 2 to 7 (excluding)
sublist1 = numbers[2:7]  # [3, 4, 5, 6, 7]
# Copying the entire list
list_copy = numbers[:]
# Reversing the list
reversed_list = numbers[::-1]  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# Getting elements with step 2, starting from index 0
stepped_list = numbers[::2]  # [1, 3, 5, 7, 9]

Slices return a new object and do not modify the original sequence (for immutable types like strings and tuples). For mutable types (lists), slices also return a new list.