Python for Programmers: List Methods
Welcome to the List Methods lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Previously, we saw that we can't write to list indexes that don't exist. However, we often need to add additional items to the end of a list. We can do that with the
.appendmethod.>
monthly_sales = [12, 6]monthly_sales.append(8)monthly_salesResult:
[12, 6, 8]
We can call
.popto remove elements from the end of the list.>
contest_entrants = ["Amir", "Betty", "Cindy"]contest_entrants.pop()contest_entrantsResult:
['Amir', 'Betty']
.popreturns the value that it removed.>
contest_entrants = ["Amir", "Betty", "Cindy"]last_entrant = contest_entrants.pop()last_entrantResult:
'Cindy'
.popis most commonly used to remove the last element, as shown above. But it can also remove other elements if we pass an optional index argument.>
remaining_tasks = ["A", "B", "C"]middle_task = remaining_tasks.pop(1)middle_taskResult:
'B'
>
remaining_tasks = ["A", "B", "C"]remaining_tasks.pop(1)remaining_tasksResult:
['A', 'C']
The
.insertmethod inserts a value at a given index. For example, we might insert a new value at index 1. All existing values at indexes 1 and higher move up by one to make room for the new value. The value at index 1 moves to 2, the value at index 2 moves to 3, etc.>
word_list = ["apple", "car", "dog"]word_list.insert(1, "bagel")word_listResult:
We can combine
.popand.insertto "rotate" a list. Rotating a list means moving the last element to the beginning of the list (or vice-versa).>
job_queue = ["A", "B", "C", "D"]job = job_queue.pop()job_queue.insert(0, job)job_queueResult:
['D', 'A', 'B', 'C']
The
inoperator checks for whether a list contains a value. It returns a boolean value,TrueorFalse.>
"Betty" in ["Amir", "Betty", "Cindy"]Result:
True
We can also use
value not in some_list, which is the opposite ofvalue in some_list.>
winners = [1, 2, 3, 5]4 not in winnersResult:
True
value not in some_listis "syntactic sugar" fornot (value in some_list). While either form works, thenot inform is generally considered more idiomatic in Python code.("Syntactic sugar" is programming language syntax that exists to provide a minor convenience, even though we could get the same result using other syntax.)
>
winners = [1, 2, 3, 5]not (4 in winners)Result:
True
>
winners = [1, 2, 3, 5]5 not in winnersResult:
False
These
inandnot inoperators work with most collection data types in Python. We'll see more examples later in the course.It's common to convert other data types into lists. For example, we might want to turn a string into a list of its individual characters, with each character in a separate string of length 1. We can do that by calling
list(some_string).>
pet = "cat"list(pet)Result:
['c', 'a', 't']
We haven't seen many data types yet, but future lessons will call
list(...)on a wide array of data types.Here's a code problem:
Finish the incomplete
rotate_leftandrotate_rightfunctions below.rotate_leftshould move the first element to the end of the list, shifting all other elements to the "left" to make room for it. For example,["a", "b", "c"]becomes["b", "c", "a"].rotate_rightshould move the last element to index 0, shifting all other elements to the "right" to make room for it. For example,["a", "b", "c"]becomes["c", "a", "b"].
You can do this with a combination of the
.popmethod (with and without an index argument),.appendmethod, and.insertmethod. There's no need for a loop, and you don't need to use the indexing operator (some_list[some_index]) at all.The functions can modify the original list, or they can create a copy and modify the copy. Either way, they should return the final list.
# These solutions don't handle the case where the list is empty. Your solutions# may not handle that case either. That's OK! Here, we're only focused on the# array methods themselves.def rotate_left(the_list):the_list.append(the_list.pop(0))return the_listdef rotate_right(the_list):the_list.insert(0, the_list.pop())return the_listassert rotate_left(["a"]) == ["a"]assert rotate_left(["a", "b"]) == ["b", "a"]assert rotate_left(["a", "b", "c"]) == ["b", "c", "a"]assert rotate_right(["a"]) == ["a"]assert rotate_right(["a", "b"]) == ["b", "a"]assert rotate_right(["a", "b", "c"]) == ["c", "a", "b"]- Goal:
No errors.
- Yours:
No errors.