Working with Lists
A list stores several values in one variable. We learn to access items by index, add and remove them, and loop over a list.
All topics (6 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
If we need to store the grades of 30 students, creating 30 separate variables is inconvenient. A list (list) solves this: it keeps items in square brackets separated by commas, for example marks = [5, 4, 5, 3, 4]. A list can also hold values of different types.
Items are numbered starting from zero, and this number is called an index. marks[0] is the first item (5), marks[2] is the third. A negative index counts from the end: marks[-1] is the last item. The len(marks) function returns the length, and changing an item is simple: marks[1] = 5.
There are methods for modifying a list. marks.append(4) adds an item at the end, marks.insert(0, 3) inserts at a given position, marks.remove(3) deletes the first 3 found, and marks.sort() sorts in ascending order. The functions sum(marks), min(marks) and max(marks) find the total, the smallest and the largest value.
You can go through the items of a list with a for loop: for m in marks: and print(m) inside. To calculate the average grade, it is enough to write print(sum(marks) / len(marks)). To check whether a value is present, use the condition if 5 in marks:.
Key takeaways
- A list stores several values in one variable:
[1, 2, 3]. - Indexes start at 0;
len()returns the length. append,insert,removeandsortmodify a list.- A
forloop goes through the items of a list one by one.
Practice tasks
- For the list
marks = [5, 3, 4, 5, 2, 4]write a program that prints the average, the highest and the lowest grade. - Ask the user for 5 numbers, add them to a list with
append, and then print the sorted list. - Write a program that counts the even numbers in a list: inside a
forloop use the conditionif x % 2 == 0:.
Review questions
Test yourself: think first, then reveal the answer.
1What are `a[1]` and `a[-1]` if `a = [10, 20, 30]`?Show answerHide answer
`a[1]` = 20 (indexes start at zero) and `a[-1]` = 30 (the last item).2How do the `append()` and `insert()` methods differ?Show answerHide answer
`append()` adds an item to the end of the list, while `insert()` puts it at any chosen position.
0 of 11 topics completed
Sign in to mark