Lists: Adding, Removing and Sorting

A list is an ordered, changeable collection. Use a queue of people to try append, insert, pop, remove and sort.

Python · beginner · 7 min · 8 steps · free

What you'll learn

lists.py

queue = ["ana", "ben"]
queue.append("cara")          # add to the end
queue.insert(0, "dev")        # add at a position
served = queue.pop(0)         # remove and return the first
queue.remove("ben")           # remove by value
queue.sort()
size = len(queue)
print(served, queue, size, "cara" in queue)

Step by step

  1. A list of two names. Lists keep their order and can change.
  2. append adds to the end.
  3. insert(0, …) puts "dev" at position 0, pushing everyone back.
  4. pop(0) removes the first item and hands it back: "dev" is served.
  5. remove("ben") deletes the first item equal to "ben".
  6. sort() puts the list in order in place. It changes this list and returns nothing.
  7. size is created with the value 2.
  8. The same list object changed four times; it now holds ["ana", "cara"].

Common mistakes

Best practices

Key takeaways

Check yourself

nums = [3, 1]; nums.append(2). What is nums?

Answer: [3, 1, 2]. append adds to the end without sorting.

What does x = [2, 1].sort() make x?

Answer: None. sort returns None.

·

More in Collections