Removing a List Element by Value or Position

The value-based removal of a list element finds a matching value. Position-based removal identifies which occurrence by index.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Keep repeated entries distinct
  2. Choose the absent outcome
  3. Choose which duplicate is meant
  4. Check changes after each removal

Keep repeated entries distinct

In ["red", "blue", "red"], removing the first matching red leaves blue, red. Removing index two leaves red, blue. Zero-based indexing tells you which position to pass. Use the correct operation when two equal records have different source positions.

Choose the absent outcome

Python remove raises an error for an absent value. pop accepts an index and returns the removed item but errors on an invalid position. Document the expected state and return value as part of mutation by a function.[1]

Choose which duplicate is meant

With ["red", "blue", "red"], removing by the value red removes the first occurrence under Python list semantics. Removing by index two instead deletes the last entry and preserves the blue at position one. If the result includes an identified record from a selection interface, the selected position may have changed due to earlier edits. A stable record identity can target the intended object across those edits. See object identity and equality.

Check changes after each removal

Deleting ascending positions one and three from the original [A, B, C, D, E] by two immediate positional removals removes B, then E from the shorter list. To target the original positions one and three, remove in descending order or build a result by scanning original positions. A test with adjacent deletions catches another version of the same bug. Specify the outcome of trying to remove a missing value. See mutating a list during iteration.

References

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