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 don’t have to be the same type. The following list contains a string, a float, an integer, and another list.
["hello", 2.0, 5, [10, 20]]
A list within another list is said to be nested and the inner list is often called a sublist.
Finally, there is 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.
1
vocabulary = ["iteration", "selection", "control"]
2
numbers = [17, 123]
3
empty = []
4
mixedlist = ["hello", 2.0, 5*2, [10, 20]]
5
6
print(numbers)
7
print(mixedlist)
8
newlist = [ numbers, vocabulary ]
9
print(newlist)
10
(chp09_01)
Check your understanding
list-2-1: A list can contain only integer items.