🐍

List Methods and Operations

Programare Python Intermediate 5 min read

List Methods and Operations

Adding Methods

  • append(x) - Adds x to end
  • extend(iterable) - Adds all elements from iterable
  • insert(i, x) - Inserts x at index i

Removing Methods

  • remove(x) - Removes first occurrence (ValueError if not found)
  • pop() - Removes and returns last (or at index)
  • clear() - Removes all elements
  • del list[i] - Deletes element at index

Search Methods

  • index(x) - Returns index of first x
  • count(x) - Returns count of x

Sorting

  • sort() - Sorts in-place, returns None
  • sorted(list) - Returns new sorted list
  • reverse() - Reverses in-place
  • reversed(list) - Returns iterator

Copying

  • list[:] or list.copy() - Shallow copy
  • copy.deepcopy(list) - Deep copy

Key Points

  • append() adds ONE element, extend() adds MULTIPLE
  • sort() modifies list, sorted() creates new
  • Shallow copy shares nested objects
  • pop() returns removed element, remove() doesn’t

📚 Related Articles