4. Add and remove
List methods are functions attached to a list. You call them with list.method(...). These methods change the list in place; except for pop(), they return None.
| Call | What it does |
|---|---|
list.append(value) | adds value at the end |
list.insert(index, value) | inserts value before index |
list.extend(other) | adds every element of other at the end |
list.remove(value) | removes the first element equal to value |
list.pop(index=-1) | removes and returns the element at index; the default is the last |
list.clear() | removes all elements |
insert() shifts the existing elements to the right. pop() is the only method in this table that gives a value back.
Add at the end
Create songs with "Song A" and "Song B". Add "Song C" at the end with append(), then print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Insert at a position
Create colors with "red" and "blue". Insert "green" at index 1 with insert(), then print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Add every element of another list
Create numbers = [1, 2]. Add all the elements of [3, 4] at the end with extend(), then print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remove by value
Create letters with "a", "b", "c" and "b". Remove the first "b" with remove(), then print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remove and return the last element
Create stack = [1, 2, 3]. Remove the last element with pop() and store the result in last. Print last, then print stack.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remove everything
Create items = ["a", "b", "c"]. Remove all elements with clear(), then print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.