Skip to content
dreamcode
dreamcode
Map
List methods
Lesson 27 of 77
+15 XP on finish
COLLECTIONSChapter 5 · Collections

List methods

Lists change in place with methods: .append(x) adds to the end, .insert(i, x) adds at a position, .remove(x) deletes the first match, .pop() removes and returns the last item, and .sort() puts the list in order. sorted(items) returns a new sorted list and leaves the original alone. x in items checks membership and items.index(x) finds a position.

Worked example

How it reads

  • .append, .insert, .remove and .pop change the list itself
  • .pop() also hands back the item it removed
  • sorted(planets) makes a new list, planets.sort() reorders the original
Common mistakes
  • planets = planets.sort() sets planets to None: .sort() changes the list and returns nothing.
  • .remove(x) raises ValueError when x is not in the list. Check with in first.
Cloud tip: Reach for sorted() when you still need the original order later, and .sort() when you do not.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Add "Mira" to the end, remove "Nova", then print the list: ['Luka', 'Mira'].

Press Run to check your work.