= [1, 2, 3]
numbers print(numbers)
[1, 2, 3]
Until now we have worked with values and variables that hold one value or string. Now we will go into other data types that can combine multiple values or strings.
Lists are common data structures to hold a sequence of elements. We can create a list by putting values inside square brackets and separating the values with commas.
= [1, 2, 3]
numbers print(numbers)
[1, 2, 3]
Each element can be accessed by an index. The index of the first element in a list in Python is 0 (in some other programming languages that would be 1).
print("The first element in the list numbers is: ", numbers[0])
The first element in the list numbers is: 1
type(numbers)
list
A total number of items in a list is called the ‘length’ and can be calculated using the len()
function.
len(numbers)
3
You can do various things with lists. E.g. it is possible to sum the items in a list (when the items are all numbers)
print("The sum of the items in the list is:", sum(numbers))
print("The mean of the items in the list is:", sum(numbers)/len(numbers))
The sum of the items in the list is: 6
The mean of the items in the list is: 2.0
What happens here:
3] numbers[
IndexError: list index out of range
This error is expected. The list consists of three items, and the indices of those items are 0, 1 and 2.
-1] numbers[
3
Yes, we can use negative numbers as indices in Python. When we do so, the index -1 gives us the last element in the list, -2 the second to last, and so on. Because of this, numbers[2] and numbers[-1] point to the same element.
2] == numbers[-1] numbers[
True
It is also possible to combine strings in a list:
= ["cat", "dog", "horse"]
words 1] words[
'dog'
type(words)
list
if type(words) == type(numbers):
print("these variables have the same type!")
these variables have the same type!
It is also possible to combine values of different type (e.g. strings and integers) in a list
= ["cat", 1, "horse"] newlist
The type of the variable newlist is list
. The elements of the list have their own data type:
type(newlist[0])
str
type(newlist[1])
int
It is possible to add numbers to an existing list using list.append()
4)
numbers.append(print(numbers)
[1, 2, 3, 4]
Using the index of an item, you can replace the item in a list:
2] = 333
numbers[print(numbers)
[1, 2, 333, 4]
Now what do you do if you do not know the index but you know the value of an item that you want to find in a list. How to find out at which position the value is listed?
= newlist.index("cat")
index print("'cat' can be found at index", index)
print(newlist[index])
'cat' can be found at index 0
cat
A tuple is similar to a list in that it’s a sequence of elements. However, tuples can not be changed once created (they are “immutable”). Tuples are created by placing comma-separated values inside parentheses ()
(instead of square brackets []
).
# Tuples use parentheses
= (1, 2, 3)
a_tuple = ('blue', 'green', 'red')
another_tuple
# Note: lists use square brackets
= [1, 2, 3] a_list
1] = 5
a_list[print(a_list)
[1, 5, 3]
1] = 5
a_tuple[print(a_tuple)
TypeError: 'tuple' object does not support item assignment
Here we see that once the tuple is created, we cannot replace any of the values inside of the tuple.
type(a_tuple)
tuple
A dictionary is another way to store multiple items into one object. In dictionaries, however, this is done with keys and values. In dictionaries, keys are typically use to look up values. A good analogy may be the contact list in your phone where you use a name (key) to lookup a phone number (value). This can be useful for several reasons, one example is to store model settings, parameters or variable values for multiple scenarios.
= {'one': 1, 'two': 2}
my_dict my_dict
{'one': 1, 'two': 2}
We can access dictionary items by their key:
'one'] my_dict[
1
And we can add new key-value pairs like that:
'three'] = 3
my_dict[ my_dict
{'one': 1, 'two': 2, 'three': 3}
Dictionary items are key-value pairs. The keys are changeable and always have to be unique (within a dictionary object). The values within a dictionary are changable, and don’t have to be unique.
'two'] = 5
my_dict[ my_dict
{'one': 1, 'two': 5, 'three': 3}
print("Dictionary keys: ", my_dict.keys())
print("Dictionary values: ", my_dict.values())
print("Dictionary items (key, value): ", my_dict.items())
Dictionary keys: dict_keys(['one', 'two', 'three'])
Dictionary values: dict_values([1, 5, 3])
Dictionary items (key, value): dict_items([('one', 1), ('two', 5), ('three', 3)])
Let’s have a look at our list again. One way to print each number is to use three print statements:
= [5, 6, 7]
numbers print(numbers[0])
print(numbers[1])
print(numbers[2])
5
6
7
A more efficient (less typing) and reliable way to print each element of a list is to loop over the list using a for loop:
for item in numbers:
print(item)
5
6
7
The improved version uses a for loop to repeat an operation — in this case, printing — once for each item in a sequence. Note that (similar to if statements) Python needs indentation (4 whitespaces) to determine which lines of code are part of the for loop.
If we want to also get the index, we can use the built-in function enumerate:
= ["cat", "dog", "horse"]
words
for index, item in enumerate(words):
print(index)
print(item)
0
cat
1
dog
2
horse
For loops can also be used with dictionaries. Let’s take our dictionary from the previous section and inspect the dictionary items
for item in my_dict.items():
print(item, "is of type", type(item))
('one', 1) is of type <class 'tuple'>
('two', 5) is of type <class 'tuple'>
('three', 3) is of type <class 'tuple'>
We can extract the keys and values from the items directly in the for
statement:
for key, value in my_dict.items():
print(key, "->", value)
one -> 1
two -> 5
three -> 3
Exercises
Now go back to your browser to morning_exercises.ipynb and continue with exercises 4-7.
When you finished the exercises, continue to chapter Write your own Python function