Sobes.tech
Senior

Name a few list methods in Python that come to mind immediately.

sobes.tech AI

Answer from AI

Here are some commonly used list methods in Python:

  • append(x) — adds element x to the end of the list.
  • extend(iterable) — extends the list by appending elements from the iterable.
  • insert(i, x) — inserts element x at position i.
  • remove(x) — removes the first element with value x.
  • pop([i]) — removes and returns the element at position i (defaults to the last element).
  • index(x[, start[, end]]) — returns the index of the first element with value x.
  • sort() — sorts the list in place.
  • reverse() — reverses the list in place.

Example:

lst = [1, 2, 3]
lst.append(4)       # [1, 2, 3, 4]
lst.remove(2)       # [1, 3, 4]
last = lst.pop()    # last = 4, lst = [1, 3]
lst.insert(1, 5)    # [1, 5, 3]
lst.sort()          # [1, 3, 5]