← Back to Python Course | Chapter 6: Data Structures | Lesson 2 of 12

Python List Methods

Adding Items

append() adds a single item to the end in O(1) time, insert(i, x) places an item at a specific position (shifting everything after it), and extend() merges another iterable's items in one at a time -- extend(other_list) is very different from append(other_list), which would nest the whole list as one element.

Example: Adding Items

python
items = [1, 2]
items.append(3)
items.insert(0, 0)
items.extend([4, 5])
print(items)

Removing Items

remove(value) deletes the first matching value and raises ValueError if it isn't found, pop(index) removes and returns the item at that position (defaulting to the last item), and clear() empties the list entirely -- pop() is the only one of the three that hands you back what was removed.

Example: Removing Items

python
items = [1, 2, 3, 2]
items.remove(2)
last = items.pop()
print(items, last)

Finding Items

index(value) returns the position of the first occurrence of a value (raising ValueError if absent), while count(value) tells you how many times it appears -- useful together when you need to confirm an item exists before searching for its exact location.

Example: Finding Items

python
items = [1, 2, 3, 2]
print(items.index(2))
print(items.count(2))

Sorting and Reversing

sort() rearranges the list in place using each element's natural ordering (or a custom key function) and returns None, which is why 'my_list = my_list.sort()' is a classic bug; reverse() simply flips the current order without any comparison logic.

Example: Sorting and Reversing

python
items = [3, 1, 2]
items.sort()
print(items)
items.reverse()
print(items)

Copying Lists

Writing new_list = old_list only copies the reference, so changes through either name affect the same underlying list -- copy() (or the slice trick list[:]) creates a genuinely separate list, though nested lists inside it are still shared (a shallow copy).

Example: Copying Lists

python
original = [1, 2, 3]
copy = original.copy()
copy.append(4)
print(original, copy)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.