Reading history

Python List Methods: append, sort, pop and More

4 min read 0 views

Every Python list method with examples: append, extend, insert, remove, pop, index, count, sort with key, reverse and copy, plus common traps.

Python lists come with eleven built-in methods. Some add items, some remove them, and some search or reorder the list. This lesson is a quick reference with a working example for each method, plus the traps that catch beginners: methods that return None, case-sensitive sorting and shallow copies.

In this lesson you will learn

  • Every list method and what it returns
  • How to sort by your own rule with key
  • The difference between sort() and sorted()
  • Shallow copies vs deep copies
  • How to use a list as a stack

All List Methods at a Glance

MethodChanges the list?Returns
append(x)Yes: adds x at the endNone
extend(iterable)Yes: adds every itemNone
insert(i, x)Yes: puts x at index iNone
remove(x)Yes: deletes the first xNone (error if missing)
pop(i=-1)Yes: deletes the item at iThe removed item
clear()Yes: empties the listNone
index(x)NoPosition of the first x
count(x)NoHow many times x appears
sort(key, reverse)Yes: sorts in placeNone
reverse()Yes: reverses in placeNone
copy()NoA new (shallow) list

Adding, Finding and Removing

scores = [72, 95, 68, 95, 81]
scores.append(77)
scores.extend([60, 88])
scores.insert(0, 99)
print(scores)
print(scores.index(95), scores.count(95))
removed = scores.pop(2)
scores.remove(95)
print(removed, scores)

Output

[99, 72, 95, 68, 95, 81, 77, 60, 88]
2 2
95 [99, 72, 68, 81, 77, 60, 88]

index(95) returns the first position (2) even though 95 appears twice. pop(2) removed and returned that 95, then remove(95) removed the other one.

Sorting With a key

names = ["tania", "Arif", "mitu", "Imran", "bilal"]
names.sort()
print(names)
names.sort(key=str.lower)
print(names)
print(sorted(names, key=len, reverse=True))
nums = [3, 1, 2]
print(nums.sort(), nums)

Output

['Arif', 'Imran', 'bilal', 'mitu', 'tania']
['Arif', 'bilal', 'Imran', 'mitu', 'tania']
['bilal', 'Imran', 'tania', 'Arif', 'mitu']
None [1, 2, 3]
  • A plain sort() puts capital letters before small ones, so "Imran" comes before "bilal".
  • key=str.lower sorts by the lowercase version of each name without changing the names themselves.
  • sorted() returns a new list and accepts the same key and reverse options; here it sorts by length, longest first.
  • The last line shows the classic trap: nums.sort() returns None.

Copies and Using a List as a Stack

a = [[1, 2], [3, 4]]
shallow = a.copy()
shallow[0].append(99)
print(a)
import copy
deep = copy.deepcopy(a)
deep[1].append(7)
print(a, deep)
stack = []
stack.append("page1"); stack.append("page2")
print(stack.pop(), stack)

Output

[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4]] [[1, 2, 99], [3, 4, 7]]
page2 ['page1']

copy() makes a new outer list, but the inner lists are still shared, so append(99) through the copy also changed a. copy.deepcopy() copies every level. Finally, append() and pop() together turn a list into a stack: the last item added is the first removed, like a browser’s back button. The same idea in C is covered in Stack Data Structure in C.

Common List Method Mistakes

  1. x = x.append(5). This sets x to None. Call x.append(5) on its own line.
  2. append() instead of extend(). a.append([1, 2]) adds one nested list.
  3. Using a list as a queue. pop(0) shifts every item and is slow for long lists; use collections.deque.
  4. Calling remove() without checking. Guard with if x in items:.

Practice Exercises

Exercise 1. Sort ["kiwi", "fig", "banana"] from shortest to longest word.

Show answer
print(sorted(["kiwi", "fig", "banana"], key=len))   # ['fig', 'kiwi', 'banana']

Exercise 2. How many times does 3 appear in [3, 1, 3, 3, 2]?

Show answer

[3, 1, 3, 3, 2].count(3) returns 3.

Exercise 3. Empty a list without creating a new one.

Show answer

Call items.clear(). Other names that point to the same list will see it empty too.

Frequently Asked Questions

Why does sort() return None?

It changes the list in place. Returning None reminds you that no new list was made. Use sorted() when you need a new sorted list.

How do I sort a list of numbers from largest to smallest?

Use nums.sort(reverse=True) or sorted(nums, reverse=True).

What is the fastest way to remove duplicates from a list?

list(dict.fromkeys(items)) removes duplicates and keeps the original order.

Summary

  • Most list methods change the list and return None; pop(), index(), count() and copy() return values.
  • Use key to sort by your own rule and sorted() to keep the original list.
  • copy() is shallow; use copy.deepcopy() for nested lists.
  • append() plus pop() makes a stack.
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *