Adding and removing items

Lists & Tuples, lesson 2 of 6

📋 Lists & Tuples, lesson 2 of 6

Adding and removing items

Grow and shrink lists with append, insert, pop and friends.

10 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Lists come with methods that change them:

  • append(x): add x to the end
  • insert(i, x): add x at index i
  • extend(other): add every item of another list
  • remove(x): delete the first x
  • pop(): take out the last item (or pop(i))
Example

Build a shopping cart

Insert "bananas" at index 2 and see where it lands.

Example

Serve the queue

pop returns the item it removes, so you can store it. remove just deletes.

Quiz

What does this print?

To search a list, use x in items, items.count(x) (how many times) and items.index(x) (position of the first match). remove and index raise a ValueError if the value isn't there, so check with in first.

Example

Dice statistics

Delete the if and call rolls.remove(5) directly to see the ValueError.

Lists and strings work together. text.split() breaks a string into a list of words (or split on any separator, like ","). " ".join(words) glues a list of strings back into one string.

Example

Split and join

Try joining with ", " or "\n" instead of " + ".

Quiz

What does this print?

Exercise

To-do list manager

Update todo step by step:

  1. Add "call mom" to the end.
  2. Remove "buy milk".
  3. Put "wake up" at the front.
  4. pop() the last task into next_task.