Python
double colon
slicing
sequences
subscripting

What is double colon in Python when subscripting sequences?

Interview Questions practice on Codemia

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

Browse interview questions

Understanding Double Colon (::) in Python Sequence Subscripting

In Python, sequences include lists, strings, tuples, and more. Each of these sequences can be accessed using a technique called subscripting or slicing, which allows you to extract portions of the sequence or analyze specific elements. A powerful feature of slicing is the use of the double colon (`::`) operator. This operator plays an essential role in accessing elements in slices, especially when you need to define a specific pattern or progression within the sequence elements.

Basics of Sequence Slicing

The syntax for sequence slicing is typically `sequence[start:stop:step]`. Here's a breakdown of these parameters:

  • start: The index from where the slicing begins (inclusive).
  • stop: The index where the slicing ends (exclusive).
  • step: The pace or interval at which elements are accessed within the defined range.

The Role of Double Colon (`::`)

The double colon (`::`) is used when you want to specify the `step` while slicing and might be omitted, leaving either the `start` or `stop` components blank. This capability allows for more concise and varied slicing patterns. For example:

  • `sequence[::2]`: This slice skips every other element, effectively selecting elements with an interval of two.
  • `sequence[::-1]`: This slice reverses the sequence, as the step is `-1`.

Examples Illustrating the Double Colon

Example 1: Skipping Elements

Here's an example of using `::` to create a new list by skipping every second element:

  • Conciseness: Simplifies code when defining non-contiguous slices.
  • Flexibility: Works seamlessly with positive and negative indices.
  • Versatility: Supports advanced operations like reversal and selective picking.
  • Immutable Sequences: Strings and tuples are immutable sequence types in Python. Any slicing on a string or tuple results in a new string/tuple.
  • Performance: Slicing operations are generally fast and efficient as they do not copy elements that won't be returned.

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.