Today we’ll be talking about the very basics of lists.
Here’s the video version of this article:
A list is an ordered collection of elements.
Lists can contain numbers, strings or other arbitrary types of data. We define lists with square brackets. Lists are ordered. We access list elements via square brackets:
>>> names = ["Alice", "Bernard", "Steve", "Emma", "Sam"] # a list of strings
>>> numbers = [3, 7, 12, 1, -54, 8] # a list of ints
>>> names[0]
'Alice'
>>> numbers[1] + numbers[5] # so 7 + 8 = 15
15
Lists are mutable. You can change any element:
>>> cars = ["Mercedes", "Ford", "BMW", "Toyota"]
>>> cars[2] = "Porsche"
>>> cars
['Mercedes', 'Ford', 'Porsche', 'Toyota']
A list may contain elements of different types. It may also contain lists:
['yes', 13.75, [1, 2, 'abc'], 2, True, 'x']
Membership
We can check if an element is contained or not in a list using the in and not in membership operators:
>>> rivers = ["Orinoco", "Potomac", "Nile"]
>>> "Thames" in rivers
False
>>> "Snake River" not in rivers
True