Subsection 8.2.2 Lists
A
list is a sequential collection of Python data values, where each value is identified by an index. The values that make up a list are called its
elements. Lists are similar to strings, which are ordered collections of characters, except that the elements of a list can have any type and for any one list, the items can be of different types.
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]]
Note 8.2.1.
You’ll likely see us do this in the textbook to give you odd combinations, but when you create lists you should generally not mix types together. A list of just strings or just integers or just floats is generally easier to deal with.
Subsection 8.2.3 Tuples
A
tuple, like a list, is a sequence of items of any type. The printed representation of a tuple is a comma-separated sequence of values, enclosed in parentheses. In other words, the representation is just like lists, except with parentheses () instead of square brackets [].
One way to create a tuple is to write an expression, enclosed in parentheses, that consists of multiple other expressions, separated by commas.
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
The key difference between lists and tuples is that a tuple is immutable, meaning that its contents can’t be changed after the tuple is created. We will examine the mutability of lists in detail in the next chapter.
To create a tuple with a single element (but you’re probably not likely to do that too often), we have to include the final comma, because without the final comma, Python treats the
(5)
below as an integer in parentheses:
Checkpoint 8.2.2.
A list can only contain 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.