python lists slicing data-structures

List Slicing in Python

Learning objectives

By the end of this pill you will be able to:

  • use positive and negative indices in lists;
  • apply slicing list[start:stop:step];
  • copy and reverse a list with slicing;
  • modify or delete multiple elements via slice assignment.

What is slicing

Slicing lets you select sub-sequences from a list using the syntax:

list[start : stop : step]

where:

  • start = index to begin from (inclusive, default 0);
  • stop = index to stop at (exclusive, default len(list));
  • step = increment between indices (default 1; can be negative).
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])     # [20, 30, 40]  (indices 1..3)
print(nums[:3])      # [10, 20, 30]  (from start to 2)
print(nums[3:])      # [40, 50, 60]  (from 3 to end)

Note: Indices start at 0. In slicing the right bound (stop) is never included.

Negative indices

Negative indices count from the end: -1 is the last element.

nums = [10, 20, 30, 40, 50, 60]
print(nums[-1])      # 60   (last)
print(nums[-3:])     # [40, 50, 60]
print(nums[:-2])     # [10, 20, 30, 40]  (excludes the last two)

Step and non-contiguous slicing

nums = [10, 20, 30, 40, 50, 60, 70]
print(nums[::2])     # [10, 30, 50, 70]   (every other element)
print(nums[1::2])    # [20, 40, 60]       (elements at odd positions)

Quick reversal

nums = [1, 2, 3, 4]
print(nums[::-1])    # [4, 3, 2, 1]

Omitting bounds and out-of-range

Python handles missing or out-of-range bounds safely.

nums = [10, 20, 30, 40]
print(nums[0:100])   # [10, 20, 30, 40]   (stop beyond length)
print(nums[-100:2])  # [10, 20]           (start too small)
print(nums[:])       # shallow copy of the list

Copying via slicing

a = [1, 2, 3]
b = a[:]          # new list (shallow copy)
b.append(99)
print(a, b)       # [1, 2, 3] [1, 2, 3, 99]

Note: This is a shallow copy: if the list contains mutable objects (e.g. other lists), those are shared.

Slice assignment and deletion

You can modify multiple elements at once.

Slice assignment

grades = [6, 7, 8, 9, 10]
grades[1:3] = [7.5, 8.5]   # replaces positions 1 and 2
print(grades)               # [6, 7.5, 8.5, 9, 10]

grades[3:3] = [9.5, 9.8]   # insertion (empty slice)
print(grades)               # [6, 7.5, 8.5, 9.5, 9.8, 9, 10]
# the number of values must match for stepped slices
grades[::2] = [0, 0, 0, 0]
print(grades)               # [0, 7.5, 0, 9.5, 0, 9, 0]

Deletion with del

nums = [10, 20, 30, 40, 50, 60]
del nums[1:4]        # removes 20, 30, 40
print(nums)          # [10, 50, 60]

Window selections (windowing)

Extracting consecutive blocks is useful for subsequences.

data = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
weekdays = data[:5]       # working days
weekend  = data[-2:]      # Saturday and Sunday
print(weekdays, weekend)