Execute Program

Python for Programmers: List Basics

Welcome to the List Basics lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Python's lists are what other languages call "arrays": they're mutable sequences of values, with integer indexes starting at zero.

  • >
    letters = ["a", "b", "c"]
    letters
    Result:
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    letters[0]
    Result:
    'a'Pass Icon
  • Lists can contain mixed types. For example, we can mix numbers and strings.

  • >
    user_ids = [18, "72fa", 99]
    user_ids
    Result:
  • In a previous lesson, we saw that len(some_string) gives us the length of a string. That same len function also works on lists, as well as most other types that have lengths.

  • >
    len("Hello")
    Result:
    5Pass Icon
  • >
    len(["a", "b", "c", "d"])
    Result:
    4Pass Icon
  • Calling len on values without a length raises a TypeError exception. (You can type error when a code example will cause an error.)

  • >
    len(100)
    Result:
    TypeError: object of type 'int' has no len()Pass Icon
  • Lists are mutable, which means that we can change them after they're created.

  • >
    user_ids = [18, 37, 99]
    user_ids[1] = "72fa"
    user_ids
    Result:
    [18, '72fa', 99]Pass Icon
  • However, we can only assign to indexes that already exist. If we assign to an index that's not in the list, that's an IndexError.

  • >
    visitor_log = ["Amir", "Betty", "Cindy"]
    visitor_log[3] = "Dalili"
    visitor_log
    Result:
    IndexError: list assignment index out of rangePass Icon
  • Some languages, including JavaScript, let us write to non-existent indexes. They allow that even though it usually indicates a mistake on our part. This is another place where Python is more strict or conservative than other dynamic languages.

  • Python's indexing strictness also applies to accessing elements: when we access an index that doesn't exist, Python raises an exception. By contrast, JavaScript returns undefined, which can lead to bugs that are difficult to track down.

  • >
    ["gasoline", "kerosene", "coal"][3]
    Result:
    IndexError: list index out of rangePass Icon
  • We can join two lists together with +, like we did with strings in an earlier lesson.

  • >
    my_list = ["A", "B"]
    my_list + [1, 2]
    Result:
    ['A', 'B', 1, 2]Pass Icon
  • We can only use + to build lists from other lists. If we try to add a non-list to a list, Python raises a TypeError exception. For example, we can't use + to append a new integer to a list.

  • >
    my_list = [1, 2, 3]
    my_list = my_list + 4
    my_list
    Result:
    TypeError: can only concatenate list (not "int") to listPass Icon
  • When writing larger list literals, we often write one element per line for readability.

  • >
    alphabet_mnemonic = [
    "apple",
    "ball",
    "cat",
    "dog",
    "elephant"
    ]

    len(alphabet_mnemonic)
    Result:
    5Pass Icon
  • Like most languages, Python allows a trailing comma after the last element of a list.

  • >
    alphabet_mnemonic = [
    "apple",
    "ball",
    "cat",
    "dog",
    "elephant",
    ]

    len(alphabet_mnemonic)
    Result:
    5Pass Icon
  • The trailing comma makes it slightly easier to edit the list later. Trailing commas are allowed in any list, but are normally used only for multi-line lists.

  • Here's a code problem:

    Finish this first_three_elements function. It takes a list, then returns a list with only the first three elements. It doesn't need to handle lists with fewer than three elements.

    def first_three_elements(the_list):
    return [the_list[0], the_list[1], the_list[2]]
    assert first_three_elements([1, 2, 3]) == [1, 2, 3]
    assert first_three_elements([0, 2, 4, 6, 8]) == [0, 2, 4]
    assert first_three_elements([5, 3, 2, 1, 6]) == [5, 3, 2]
    assert first_three_elements([1, 4, 9, 16, 25]) == [1, 4, 9]
    Goal:
    None
    Yours:
    NonePass Icon