Data structures · Lesson 7 of 18 · 18 min

Sequences

Lists, tuples, slicing, and in-place versus copy.

  • Slice with start:stop:step fluently
  • Know list methods that mutate vs copy
  • Use tuples for fixed records

A sequence is ordered and indexable

Lists, tuples, strings, ranges, and bytes all share a contract: `len`, indexing, slicing, membership, concatenation, and iteration. Lists are the mutable workhorse. Tuples are immutable records — heterogeneous by convention (`(name, port)`), and a signal that the collection is a fixed row, not a bag of items.

A trailing comma makes a one-element tuple: `(1,)` not `(1)`. Parentheses are for grouping; the comma is the tuple constructor.

Slicing is a copy for lists
xs = [0, 1, 2, 3, 4, 5]
print(xs[1:4], xs[:3], xs[3:], xs[::2], xs[::-1])
head, *rest, last = xs
print(head, rest, last)
ys = xs[:]
ys[0] = 99
print(xs, ys)

List operations that bite

CallMutates?Returns
xs.append(x)yesNone
xs.extend(it)yesNone
xs.sort()yesNone
sorted(xs)nonew list
xs.reverse()yesNone
xs.pop()yesthe item
xs + ysnonew list

Slicing assignment

You can replace a stretch of a list: `xs[1:4] = [9, 9]`. The replacement does not have to be the same length. `xs[:] = other` replaces all contents without rebinding the name — useful when other names alias the same list.

`copy.copy(xs)` and `xs[:]` are shallow. Nested lists are shared. If you need independence all the way down, `copy.deepcopy`.

In-place replace versus rebind
a = [1, 2, 3]
b = a
a[:] = [7, 8]
print("alias sees in-place:", b)
a = [9]
print("rebind leaves alias:", b, "a is", a)

Check yourself

Quiz

  1. 1.What is `(3)`?

  2. 2.`xs.sort()` returns:

  3. 3.`xs[::-1]` on a list:

Practice

Exercise

Write `middle(xs)` that returns a new list of all items except the first and last. If the list has fewer than 2 items, return an empty list. Do not mutate xs.

Tutor

Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.