10.2. 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"]

The first example is a list of four integers. The second is a list of three strings. As we said above, the elements of a list have to be the same type. There is also a special list that contains no elements. It is called the empty list and is denoted [].

As you would expect, we can also assign list values to variables and pass lists as parameters to functions. Like other variables, when creating a list variable the type must be specified when it is declared. Unlike other variables, the list type changes depending on the type of the elements in the list. List types use square brackets ( [ and ]) to surrond the type of the elements in the list.

 
1
vocabulary: [str]
2
numbers: [int]
3
empty: [bool]
4
5
vocabulary = ["iteration", "selection", "control"]
6
numbers = [17, 123]
7
empty = []
8
9
print(str(vocabulary))
10
print(str(numbers))
11
print(str(empty))
12

(chp09_01)

Check your understanding

list-2-1: A list can contain only integer items.




You have attempted 1 of 3 activities on this page
Next Section - 10.3. List Length