Lists
Python supports a number of compound data types, which group other values together. The most versatile is the list, which can be written as a sequence of comma-separated values, or items between square brackets. A list might contain items of different types, but usually the items all have the same type:
squares = [1, 4, 9, 16, 25]
squares
The output is:
[1, 4, 9, 16, 25]
Like strings and all other built-in sequence types, lists can be indexed and sliced:
squares[0] # Indexing returns the item.
The output is:
1
This example shows a negative index:
squares[-1]
The output is:
25
This example shows how slicing returns a new list:
squares[-3:] # Slicing returns a new list.
The output is:
[9, 16, 25]
All slice operations return a new list that contains the requested elements. So, the following slice returns a new, shallow copy of the list:
squares[:]
The output is:
[1, 4, 9, 16, 25]
Lists also support concatenation using the plus ("+") operator:
squares + [36, 49, 64, 81, 100]
The output is:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike strings, which are immutable, lists are a mutable type. That is, you can change any value in the list. Suppose you define a list that contains an incorrect item:
cubes = [1, 8, 27, 65, 125] # Something's wrong here...
4 ** 3 # The cube of 4 is 64, not 65!
The output is:
64
Here's how to correct the item and display the result:
cubes[3] = 64 # Replace the wrong value.
cubes
The output is:
[1, 8, 27, 64, 125]
You can assign to slices, which can change the size of the list or clear it entirely. First, create a new list:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters
The output is:
['a', 'b', 'c', 'd', 'e', 'f', 'g']
Then, you can replace some values using a slice:
# Replace some values.
letters[2:5] = ['C', 'D', 'E']
letters
The output is:
['a', 'b', 'C', 'D', 'E', 'f', 'g']
Here's how to remove values from the list:
# Now remove them.
letters[2:5] = []
letters
The output is:
['a', 'b', 'f', 'g']
This example shows how to clear the list:
# Clear the list by replacing all the elements with an empty list.
letters[:] = []
letters
The output is:
[]
The built-in len() function also applies to lists. Use it to get the length of a list:
letters = ['a', 'b', 'c', 'd']
len(letters)
The output is:
4
You can nest lists. That is, you can create a list that contains other lists. For example:
a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
x
The output is:
[['a', 'b', 'c'], [1, 2, 3]]
x is a list of lists. You can access its constituent lists by using the same indexing that you use with simpler lists:
x[0]
The output is:
['a', 'b', 'c']
And, by specifying additional index numbers, you can directly access elements within those constituent lists:
x[0][0]
The output is:
'a'
Try it yourself
Nested lists come up a lot in programming, so it pays to practice.
- Which indices would you include after
xto get the outputc? - How about to get the output
3?
Hint (expand to reveal)
x[0][2]
x[1][2]