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 (1)

Collapse
 
gimi5555 profile image
Gilder Miller

Python lists come with built-in tools to change, organize, and inspect data without extra effort.
To add items, use append() for single values, insert() for a specific position, and extend() to merge another list.
To remove items, remove() deletes the first match, pop() removes by index (or last item if empty), and clear() wipes the whole list.
For ordering, sort() changes the list directly, while reverse() flips it in place.
You can also inspect data with count() to see occurrences and index() to find the first position of a value.
Most of the time, you combine these methods to quickly shape lists into whatever structure your program needs.