Skip to main content

Section 9.3 List Values

There are several ways to create a new list. The simplest is to enclose the elements in square brackets ( [ and ]).
[10, 20, 30, 40]
["spam", "bungee", "swallow"]
[22.5, 23.1, 24.0, 22.9, 26.1, 25.7, 27.8]
The first example is a list of four integers, the second is a list of three strings, and the third is our list of temperatures—a list of floating-point numbers.
As we said in Section 9.1, the elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and a boolean.
["hello", 2.0, 5, False]
As you might expect, we can also assign list values to variables and pass lists as parameters to functions. The len function can take a list as its argument, and it will return the number of elements in the array.

Checkpoint 9.3.1.

    A list can contain only integer items.
  • False
  • Yes, unlike strings, lists can consist of any type of Python data.
  • True
  • Lists are heterogeneous, meaning they can have different types of data.

Checkpoint 9.3.2.

    What is printed by the following statements?
    a_list = [3, 67, "cat", 3.14, False]
    print(len(a_list))
    
  • 4
  • len returns the actual number of items in the list, not the maximum index value.
  • 5
  • Yes, there are 5 items in this list.