Data—lists and collections

Objectives

  • Be able to define a list and use some of its key functions.
  • Know how to access list elements.

In this lesson, we’re going to investigate how we can represent a collection of data in Python using a data type called a list. Some of this will be familiar from the lesson on strings, because they share many of the same properties and features as lists.

Creating lists

Let’s begin by creating a list. We do this by listing a series of values, separated by commas, and enclosing them within square brackets. For example:

apples = [2, 4, 6, 5]

We’ve created a variable named apples that refers to a list with 4 items, where each item is a number.

We can also use functions to create lists. One function in particular that is often encountered and is very useful is range. When provided with one argument, the range function generates a list of numbers from 0 up to, but not including, the value of the argument. For example:

print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Similar to how we accessed multiple list elements, we can also provide the range function with start and end values:

print range(2, 10)
[2, 3, 4, 5, 6, 7, 8, 9]

List functions

Similar to strings, lists have a set of functions attached to them that are often quite useful. For example, the append function can be used to add additional elements to the list. So if we wanted to add another element, the number 2, we could run:

apples = [2, 4, 6, 5]

print apples

apples.append(2)

print apples
[2, 4, 6, 5]
[2, 4, 6, 5, 2]

We can use another function, count, to determine how many elements in the list match a particular target value. For example:

apples = [2, 4, 6, 5, 2]

print apples.count(2)
print apples.count(4)
print apples.count(1)
2
1
0

An important property of lists is that they don’t need to have elements that are all of the same type. For example, it is fine to mix strings and numbers in the same list. Lists can even contain other lists, which is an important concept. For example:

apples = ["a", 1, "b", 2]

print apples

apples = [["a", 1], ["b", 2]]

print apples
['a', 1, 'b', 2]
[['a', 1], ['b', 2]]

Accessing list elements

We can access the individual elements of a list just like we did with strings. For example:

apples = [["a", 1], ["b", 2]]

print apples[0]
print apples[0][0]
['a', 1]
a

The last example in the above is an extension of what we’ve covered already, and shows how element access can be chained together. In this example, we access the first element (zeroth index) of apples, which is the list ["a", 1]. We then access the first element (zeroth index) of this list, which is "a".