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.

Activity: CodeLens 2 (Simple_Lists)

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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.

You have attempted 1 of 6 activities on this page