Execute Program

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 .append method.

  • >
    monthly_sales = [12, 6]
    monthly_sales.append(8)
    monthly_sales
    Result:
    [12, 6, 8]Pass Icon
  • We can call .pop to remove elements from the end of the list.

  • >
    contest_entrants = ["Amir", "Betty", "Cindy"]
    contest_entrants.pop()
    contest_entrants
    Result:
    ['Amir', 'Betty']Pass Icon
  • .pop returns the value that it removed.

  • >
    contest_entrants = ["Amir", "Betty", "Cindy"]
    last_entrant = contest_entrants.pop()
    last_entrant
    Result:
    'Cindy'Pass Icon
  • .pop is 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_task
    Result:
    'B'Pass Icon
  • >
    remaining_tasks = ["A", "B", "C"]
    remaining_tasks.pop(1)
    remaining_tasks
    Result:
    ['A', 'C']Pass Icon
  • The .insert method 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_list
    Result:
  • We can combine .pop and .insert to "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_queue
    Result:
    ['D', 'A', 'B', 'C']Pass Icon
  • The in operator checks for whether a list contains a value. It returns a boolean value, True or False.

  • >
    "Betty" in ["Amir", "Betty", "Cindy"]
    Result:
    TruePass Icon
  • We can also use value not in some_list, which is the opposite of value in some_list.

  • >
    winners = [1, 2, 3, 5]
    4 not in winners
    Result:
    TruePass Icon
  • value not in some_list is "syntactic sugar" for not (value in some_list). While either form works, the not in form 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:
    TruePass Icon
  • >
    winners = [1, 2, 3, 5]
    5 not in winners
    Result:
    FalsePass Icon
  • These in and not in operators 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']Pass Icon
  • 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_left and rotate_right functions below.

    • rotate_left should 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_right should 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 .pop method (with and without an index argument), .append method, and .insert method. 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_list

    def rotate_right(the_list):
    the_list.insert(0, the_list.pop())
    return the_list
    assert 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.Pass Icon