Python
slicing
programming
coding
Python tutorial

How slicing in Python works

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Slicing is a hugely useful feature in Python that allows for extracting parts of sequences, such as lists, tuples, and strings. Slicing provides a way to access a subset of items within a data structure by specifying a start, stop, and step value, all within the bracket syntax of sequence[start:stop:step].

Basic Syntax and Parameters

The basic syntax for slicing is:

python
sequence[start:stop:step]
  • start: The beginning index of the slice. It is inclusive, so the element at this position is part of the slice.
  • stop: The end index of the slice. It is exclusive, meaning the element at this position is not part of the slice.
  • step: The step size for slicing. Default is 1, which means consecutive elements are selected.

Default Parameter Values

When not specified, start, stop, and step default to:

  • start = 0
  • stop = size_of_sequence
  • step = 1

Examples of Slicing

python
1# Define a list
2numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3
4# Basic slicing
5print(numbers[2:7])     # Output: [2, 3, 4, 5, 6]
6
7# Slicing with a step
8print(numbers[2:9:2])   # Output: [2, 4, 6, 8]
9
10# Omitting 'start' and 'stop' to use their default values
11print(numbers[:5])      # Output: [0, 1, 2, 3, 4]
12print(numbers[5:])      # Output: [5, 6, 7, 8, 9]
13
14# Full slice
15print(numbers[:])       # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
16
17# Negative slicing
18print(numbers[-3:])     # Output: [7, 8, 9]
19print(numbers[:-3])     # Output: [0, 1, 2, 3, 4, 5, 6]

Negative Indices and Steps

Python allows the use of negative indices for slicing. Negative steps can be used to reverse a sequence.

python
1# Negative indices
2print(numbers[-5:-2])   # Output: [5, 6, 7]
3
4# Reverse the sequence
5print(numbers[::-1])    # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
6
7# Reverse part of the sequence
8print(numbers[7:2:-1])  # Output: [7, 6, 5, 4, 3]

Advanced Slicing Techniques

Multi-Dimensional Arrays

For multi-dimensional arrays such as those provided by packages like NumPy, each dimension can be sliced independently:

python
1import numpy as np
2
3# Create a 2D numpy array
4array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
5
6# Slice the first two columns of every row
7print(array[:, :2])     # Output: [[1 2] [4 5] [7 8]]
8
9# Slice even-indexed rows and reverse columns
10print(array[::2, ::-1]) # Output: [[3 2 1] [9 8 7]]

Performance of Slicing

Slicing is efficient as it does not create a new copy of the original data structure, but rather creates a new view or references to the elements in the range specified, unless explicitly enforced (e.g., using [:] on a list).

Practical Scenarios

  • Data Management: Slicing is used for data preparation tasks, such as extracting subsets of data for training machine learning models.
  • Text Processing: In string manipulation, slicing helps in fetching substrings that are needed for parsing or formatting.
  • Image Processing: In graphic applications, parts of image data can be processed using slicing techniques.

Summary Table

ParameterDescriptionDefault Value
startBeginning index of the slice0
stopOne past the end index of the slicesize_of_sequence
stepStep size for slicing1
NegativeIndices can be negative to count backwardsSupported
PerformanceNo memory overhead for standard slicingEfficient as it creates a view

Understanding and using slicing in Python empowers you to efficiently and effectively manage data structures, laying the foundational knowledge needed for more sophisticated data manipulation and exploration tasks.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.