Lists
Lists are a way to store multiple pieces of similar data into one variable. They can contain any type of variable and they can contain as many variables as you wish. Here is an example of how to build a list.
mylist = [1,2,3]
print(mylist)
You can also access individual elements of a list. Here, for example, the second element of the list is acesssed and printed. Note that python starts to count at the index 0. Therefore the second element has the index 1: mylist = [1, 2, 3] print(mylist[1])
You can also dynamically modify lists by using e.g. the append() method:
mylist = [0]
mylist.append(1)
print(mylist)
mylist.append(2)
print(mylist)
Accessing an index which does not exist generates an exception (an error).
mylist = [1,2,3]
print(mylist[10])
You can also use the indexing brackets [] to change a certain list entry:
mylist = [1,5,5]
mylist[1] = 3
print(mylist)
Lists can also contain strings (or any other type of variable):
mylist = ["Hallo", "Name"]
print(mylist)
They can even contain other lists (while this doesn't happen so often):
mylist = ["apple", "apple", "peach"]
otherlist = [1, 2, 3]
# This is a list where other lists are put into.
listoflists = [mylist, otherlist]
# This prints both lists that are in listoflists
print(listoflists)
# This only prints the second list:
print(listoflists[1])
Exercise
In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method. You must add the numbers 1,2, and 3 to the "numbers" list, and the words 'hello' and 'world' to the strings variable.
You will also have to fill in the variable second_name with the second name in the names list, using the brackets operator []. Note that the index is zero-based, so if you want to access the second item in the list, its index will be 1.
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
# write your code here
second_name = None
# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
# write your code here
numbers.append(1)
numbers.append(2)
numbers.append(3)
strings.append("hello")
strings.append("world")
second_name = names[1]
# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)
test_output_contains("[1,2,3]", no_output_msg= "Make sure that you have printed the `numbers` list.")
test_output_contains("['hello', 'world']", no_output_msg= "Make sure that you have printed the `strings` list.")
test_output_contains("The second name on the names list is Eric", no_output_msg= "Did you fill in the variable `second_name` with the second name in the names list?")
success_msg("Great Job!")