Lesson 2.1

Lists, tuples, and slicing

A slice takes a start, a stop, and a step, and any of them can be omitted or negative.

15mBeginner25.4k students

Overview

Slicing is the most underused syntax in Python

A slice takes a start, a stop, and a step, and any of them can be omitted or negative. Reversing, taking every second element, or dropping the first and last item are all one expression.

A slice of a list is a new list, which makes it the shortest way to copy one — and a reminder that plain assignment does not copy anything.

Tuples are for fixed-length records where position has meaning: a coordinate, a database row. Lists are for variable-length collections of like things.

In this lesson you will:

  • Slice a sequence without a loop
  • Choose a tuple when the shape is fixed
  • Copy a list instead of aliasing it

Resources

Previous Lesson
Next Lesson
Lists, tuples, and slicing — Python Foundations for Data Work — Vertex