Working with Lists¶
In earlier chapters we worked with lists of numbers as shown below.
But a list in Python can also hold different types of things in the same list,
like numbers and strings. You start and end a list with square brackets
([]
) and separate elements with commas as shown in line 1 below. The
function len
will return the number of items in the list. You can do
“arithmetic” with lists using *
and +
, just like you can with strings.
Multiplication repeats items in the list. We can add two lists together, even
if one of the lists only has a single item in it.
-
csp-16-3-1: What is the length of the list [“Sue”, “Maria”, 5, “Erica”]?
- 1
- This is just how many numbers are in the list. There are also strings in this list.
- 3
- This is just the number of strings in this list. There is also a number in this list.
- 4
- This is the number of items in this list. There are 3 strings and 1 number.
- 14
- Count each string as one item.
- 1
- That is the number of items in the list start on line 1, but line 2 adds more.
- 2
- That is how many items were in the list that was added to start. But, start already had one element.
- 3
- The list start has one item and then two more were added.
csp-16-3-2: What would the following code print?
start = [3]
start = start + [6,7]
print (len(start))
Note
Remember that a list starts with a [
and ends with a ]
. Items in
the list are separated by commas.
Run the code below to see what type of error you get if you forget the ending
]
as shown below on line 1. Also see what happens if you don’t separate
the list items with commas as shown on line 2. Fix the code to run and print.