Sequence Repetition and Shared Elements

Repetition can duplicate references in a sequence. It may leave repeated positions sharing a single mutable object.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Work through a matrix mistake
  2. Construct independent rows
  3. Track shared rows after multiplication
  4. Use independent immutable data when sharing is deliberate

Work through a matrix mistake

In Python, [[0, 0]] * 3 yields three positions referring to one row. Changing the first cell through row zero changes that cell in all three observed rows. Names and object identity explain why mutating through one position is visible elsewhere.

Construct independent rows

Create one inner list for each row with a comprehension when a grid requires independent cells. Repeating immutable values within a row is often suitable. List comprehensions make the allocation frequency visible for each produced element.[1]

Track shared rows after multiplication

Starting with row = [0, 0], the expression grid = [row] * 3 repeats a reference to the same row three times. Assigning grid[0][1] = 4 now produces three visible rows containing four in their second position. Building three new lists with a comprehension makes that update local to the first row. Run both constructions and check identity and contents separately. See list comprehensions.

Use independent immutable data when sharing is deliberate

Repeating an immutable token such as "-" creates the desired repeated sequence without a risk of changing a token's contents. Repeating a tuple with a mutable object inside still shares that object. If every element should begin equal but evolve separately, allocate the mutable object on each iteration. Check repetition counts zero and one, since a single repetition may conceal unwanted sharing with a template. See immutable tuple shells.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩