How to Slice Lists/Arrays and Tuples in Python

Introduction to Python Slicing

In Python, slicing is used to extract parts of sequences like lists, arrays, and tuples using a specific syntax. Let's learn how!

Python Slice Syntax

Use this syntax for slicing: sequence[start:stop:step]. Start is inclusive, stop is exclusive, and step is optional.

Slicing a List

To slice a list, use my_list[start:stop]. Example: my_list[1:4] extracts elements from index 1 to 3.

Slicing Tuples

Slicing works the same with tuples: my_tuple[start:stop]. Tuples are immutable, but you can still extract portions.

Negative Indexing

You can use negative indexing for slicing, such as my_list[-3:-1], to slice from the end of the list or tuple.

Step Argument in Slicing

The step argument allows skipping elements. For example, my_list[::2] selects every second element.

Learn More at PythonCentral.io

Discover more Python tips and tutorials at PythonCentral.io. Explore coding tricks to become a Python pro!