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.
len will return the number of items in the list. You can do “arithmetic” with lists using
+, 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.
- This is just how many numbers are in the list. There are also strings in this list.
- This is just the number of strings in this list. There is also a number in this list.
- This is the number of items in this list. There are 3 strings and 1 number.
- Count each string as one item.
csp-16-3-1: What is the length of the list [“Sue”,”Maria”,5,”Erica”]?
- That is the number of items in the list start on line 1, but line 2 adds more.
- That is how many items were in the list that was added to start. But, start already had one element.
- The list start has one item and then two more were added.
csp-16-3-2: What would the following code print?
start =  start = start + [6,7] print (len(start))
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.
Discuss topics in this section with classmates.