DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python List Methods Explained Simply (Add, Remove, Sort)

Lists have built-in methods to modify them directly.

Adding items

fruits = ["apple", "banana"]

fruits.append("cherry")
print(fruits)  # ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")
print(fruits)  # ['apple', 'orange', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

Extend with multiple items:

more = ["grape", "kiwi"]
fruits.extend(more)
print(fruits)  # Adds grape and kiwi
Enter fullscreen mode Exit fullscreen mode

Removing items

fruits.remove("banana")  # Removes first "banana"
print(fruits)

popped = fruits.pop()     # Removes and returns last item
print(popped)             # kiwi

fruits.pop(0)             # Removes item at index 0
Enter fullscreen mode Exit fullscreen mode

Clear all:

fruits.clear()
print(fruits)  # []
Enter fullscreen mode Exit fullscreen mode

Sorting and reversing

numbers = [3, 1, 4, 1, 5]

numbers.sort()
print(numbers)  # [1, 1, 3, 4, 5]

numbers.reverse()
print(numbers)  # [5, 4, 3, 1, 1]
Enter fullscreen mode Exit fullscreen mode

Counting and indexing

numbers = [1, 2, 2, 3]

print(numbers.count(2))   # 2
print(numbers.index(3))   # 3 (first position)
Enter fullscreen mode Exit fullscreen mode

Simple examples

Shopping list:

shopping = ["milk", "bread"]
shopping.append("eggs")
shopping.remove("bread")
print(shopping)  # ['milk', 'eggs']
Enter fullscreen mode Exit fullscreen mode

Sort names:

names = ["bob", "alice", "charlie"]
names.sort()
print(names)  # ['alice', 'bob', 'charlie']
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Add with .append(), .insert(), .extend().
  • Remove with .remove(), .pop(), .clear().
  • Sort with .sort(), reverse with .reverse().
  • Check with .count(), .index().

Practice list methods on collections. They make working with lists efficient in Python programs.

Top comments (0)