List Methods

45 min read Working with Lists

This is a free course. Log in to run the code exercises and track your progress.

List Methods

Lists can grow and shrink. These methods change the list itself:

  • append(x): add x at the end.
  • insert(i, x): put x at index i.
  • extend(other): add every element of another list.
  • remove(x): delete the first x.
  • pop(): remove and return the last element; pop(i) the one at index i.
  • sort(): arrange in ascending order; sort(reverse=True) for descending.
  • reverse(): reverse the order.
cities = ["Delhi", "Pune"]
cities.append("Agra")       # ['Delhi', 'Pune', 'Agra']
cities.insert(0, "Kochi")   # ['Kochi', 'Delhi', 'Pune', 'Agra']
cities.remove("Pune")       # ['Kochi', 'Delhi', 'Agra']
cities.sort()               # ['Agra', 'Delhi', 'Kochi']

count(x) and index(x) only look: they return how many times x occurs and where it first occurs.

Python exercise

Read a line of integers and print them with every duplicate removed, keeping the first occurrence of each value in its original order. Use a new list and append().

nums = list(map(int, input().split()))
unique = []
for n in nums:
    pass  # append n only if it is not already in unique
print(*unique)

Log in to edit and run this code.