Introduction to Lists
In the lesson on conditions, you taught your programs to make decisions. This lesson is about storing many values together.
Imagine you want to keep the names of five students. With what you know so far, you would need five variables:
student1 = "Jennifer"
student2 = "Boris"
student3 = "Nancy"
student4 = "David"
student5 = "Ava"That's a lot of typing. And what if a sixth student joins the class? Every new student would need a new variable. This is what lists are for. A list stores many values in one variable:
students = ["Jennifer", "Boris", "Nancy", "David", "Ava"]The values in a list are called its elements. This list has five elements, and they keep their order: "Jennifer" is the first, "Ava" the last.
You print a list with print(), like any other value:
fruits = ["apple", "banana", "cherry"]
print(fruits)This prints:
['apple', 'banana', 'cherry']Python shows the list the way you could write it in code: in square brackets, with commas between the elements, and with text in quotes, so that you can see where each element starts and ends. Notice the quotes, though: in the code they are double, in the output they are single. That's fine. For Python, "apple" and 'apple' are the same text. When it prints a list, it writes text in single quotes.
Instructions
- 1
Print the list
students: on the next line, writeprint(students). The output should be['Jennifer', 'Boris', 'Nancy', 'David', 'Ava'].