📋 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): addxto the endinsert(i, x): addxat indexiextend(other): add every item of another listremove(x): delete the firstxpop(): take out the last item (orpop(i))
Build a shopping cart
Insert "bananas" at index 2 and see where it lands.
Serve the queue
pop returns the item it removes, so you can store it. remove just deletes.
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.
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.
Split and join
Try joining with ", " or "\n" instead of " + ".
What does this print?
To-do list manager
Update todo step by step:
- Add
"call mom"to the end. - Remove
"buy milk". - Put
"wake up"at the front. pop()the last task intonext_task.