This is an archived version of the course. Please see the latest version of the course.

Lists

Python does NOT offer fixed-sized arrays as in C++. However, it offers something arguably better out of the box – a list! A list can be modified and resized on the go.

>>> students = ["Abraham", "Bella", "Connor", "Da-ming", "Enya"]

In Python, you can mix different types of objects in the same list (whether this should be done is a different question).

>>> mixed_buffet = [1, "Two", 3.03, 4j]

You can also have a nested list, i.e. a list inside another list (and inside yet another list).

>>> list_in_list = [1, 2, [3, 4, [5, 6, 7], 8], 9, [10, 11]]

You can also use the list() constructor to construct a new list object (remember - everything is an object!)

>>> x = list("abc")    # converts the string "abc" into a list ["a", "b", "c"]
>>> print(x)

Getting the number of elements in a list

Need to know the size of a list? Use Python’s built-in len() function. In fact, you can use this for many of the other data structures we will discuss later.

>>> numbers = [1, 2, 3]
>>> print(len(numbers))