Python Array Methods
Array Methods
In Python, lists are used as arrays in everyday programming. Lists come with built-in methods that make it easy to add, remove, search, count, sort, and copy the data they hold. A method is called with dot notation:
array_name.method_name(arguments)
This lesson walks through each array (list) method with an example, the expected output, and the key detail to remember.
Important: Most Methods Change the Array in Place
Most of these methods modify the original array and return None. Only a few return a value:
| Returns a Value | Modifies the Array (Returns None) |
|---|---|
copy(), count(), index() | append(), clear(), extend(), insert(), remove(), reverse(), sort() |
pop() — modifies the array and returns the removed item |
A common mistake is writing marks = marks.sort(), which replaces your array with None.
append() — Add an Item to the End
Adds a single element to the end of the array.
colors = ["red", "blue", "green"]
colors.append("yellow")
print(colors)
Expected output:
['red', 'blue', 'green', 'yellow']
clear() — Remove All Elements
Removes every element, leaving an empty array.
numbers = [1, 2, 3, 4]
numbers.clear()
print(numbers)
Expected output:
[]
copy() — Create a Shallow Copy
Returns a new array containing the same elements.
original = ["pen", "pencil", "eraser"]
duplicate = original.copy()
original.append("marker")
print(original)
print(duplicate)
Expected output:
['pen', 'pencil', 'eraser', 'marker']
['pen', 'pencil', 'eraser']
The copy is independent: adding "marker" to original does not change duplicate. Writing duplicate = original would not copy — both names would point to the same array.
count() — Count Occurrences of a Value
Returns how many times a value appears.
scores = [85, 90, 85, 70, 85]
print(scores.count(85))
Expected output:
3
If the value is not present, count() returns 0.
extend() — Add Multiple Elements
Adds each element from another iterable to the end of the array.
list1 = ["HTML", "CSS"]
list2 = ["JavaScript", "Python"]
list1.extend(list2)
print(list1)
Expected output:
['HTML', 'CSS', 'JavaScript', 'Python']
Compare with append(), which would add the whole second list as one nested element: ['HTML', 'CSS', ['JavaScript', 'Python']].
index() — Find the Position of an Element
Returns the index of the first occurrence of a value.
animals = ["cat", "dog", "rabbit", "dog"]
print(animals.index("dog"))
Expected output:
1
"dog" appears at indexes 1 and 3, but only the first position is returned. If the value does not exist, index() raises a ValueError, so check with in first when the value might be missing.
insert() — Add an Element at a Specific Position
Inserts an element before the given index. The existing elements from that position onward shift right.
cities = ["Delhi", "Mumbai", "Chennai"]
cities.insert(1, "Bengaluru")
print(cities)
Expected output:
['Delhi', 'Bengaluru', 'Mumbai', 'Chennai']
pop() — Remove an Element by Index
Removes the element at the given index and returns it.
tasks = ["study", "exercise", "sleep"]
removed_task = tasks.pop(0)
print(removed_task)
print(tasks)
Expected output:
study
['exercise', 'sleep']
Without an index, pop() removes and returns the last element. Calling pop() on an empty array raises an IndexError.
remove() — Remove an Element by Value
Removes the first element that matches the value.
items = ["apple", "banana", "cherry", "banana"]
items.remove("banana")
print(items)
Expected output:
['apple', 'cherry', 'banana']
Only the first "banana" is removed. If the value is not found, remove() raises a ValueError.
reverse() — Reverse the Order
Reverses the elements in place.
nums = [1, 2, 3, 4, 5]
nums.reverse()
print(nums)
Expected output:
[5, 4, 3, 2, 1]
reverse() flips the current order; it does not sort. For a reversed copy that leaves the original untouched, use slicing: nums[::-1].
sort() — Sort the Array
Sorts the elements in ascending order by default.
marks = [88, 72, 95, 60, 83]
marks.sort()
print(marks)
Expected output:
[60, 72, 83, 88, 95]
Sorting in Descending Order
marks.sort(reverse=True)
print(marks)
Expected output:
[95, 88, 83, 72, 60]
Sorting by a Custom Rule
The key parameter accepts a function that decides what to compare:
names = ["Priya", "Al", "Kumaran"]
names.sort(key=len)
print(names)
Expected output:
['Al', 'Priya', 'Kumaran']
The names are sorted by length instead of alphabetically.
Tip:
sort()changes the original array. To keep the original and get a sorted copy, use the built-insorted()function:ordered = sorted(marks).
Practical Example: Managing a Queue of Orders
orders = ["ORD-101", "ORD-102"]
orders.append("ORD-103") # New order arrives
orders.insert(0, "ORD-100") # Priority order goes first
next_order = orders.pop(0) # Process the first order
print("Processing:", next_order)
print("Waiting:", orders)
print("Orders waiting:", len(orders))
Expected output:
Processing: ORD-100
Waiting: ['ORD-101', 'ORD-102', 'ORD-103']
Orders waiting: 3
append() adds to the back of the queue, and pop(0) takes from the front — a "first in, first out" pattern.
Note: For very large queues,
pop(0)is slow because every remaining element must shift. The standard library'scollections.dequeis designed for fast additions and removals at both ends.
Method Summary
| Method | Purpose |
|---|---|
append(item) | Add an item to the end |
clear() | Remove all elements |
copy() | Return a shallow copy |
count(value) | Count occurrences of a value |
extend(iterable) | Add every item from an iterable to the end |
index(value) | Return the position of the first match |
insert(index, item) | Add an item at a specific index |
pop(index) | Remove and return the item at an index (last by default) |
remove(value) | Remove the first matching value |
reverse() | Reverse the order in place |
sort() | Sort in place (ascending by default) |
Common Mistakes
| Mistake | Problem |
|---|---|
marks = marks.sort() | marks becomes None |
items.remove("x") when "x" is missing | ValueError |
items.append(a, b) | TypeError — append() takes one argument; use extend() |
backup = items to copy | Both names share the same array; use copy() |
Sorting mixed types like [3, "a"] | TypeError — values must be comparable |
Related Concepts
- Python Arrays — creating and accessing arrays
- Python Lists and Python List Methods — the full list reference
- Built-in functions such as
len(),sorted(),min(),max(), andsum()