Course 5.1Lesson 3 of 5
A for loop goes through a list, one item in each round, in the same way that it goes through a text. A loop can build a total, count the items that pass a test, and build a new list by starting with an empty list and using append. sum, max and min give quick answers, and the average is sum divided by len. To use the position as well as the item, loop over range of len, or use enumerate. Two lists in the same order work like a table.
Try the code and the simulations beside the lesson.
After this lesson you can
for loop,In the loops chapter, you wrote for letter in "python":. A list works in the same way. In each round, the loop variable holds the next item.
Then three ready-made functions do the same work in one line each.
sum(marks) adds the items.max(marks) is the biggest item.min(marks) is the smallest item.The average is the sum divided by the number of items: sum(marks) / len(marks).
So why did we write the loop at all? Because the loop is the pattern that you will need when no ready-made function exists: for example, "the total of the marks that are at least 60". Learn the pattern, and use the functions when they fit.
All three have the same shape: start before the loop, change inside, use after.
These four tools save you a loop each. Behind the scenes, each one goes through the list once.
If you remove items from a list inside a for loop over the same list, Python moves on by position, and some items are skipped. The safe way is to build a new list of the items that you want to keep, as in pattern 3.
Sometimes you need both the item and its position. Two lists in the same order work like a table: position 0 of names belongs to position 0 of marks.
A rule for choosing:
for item in a_list:.for i, item in enumerate(a_list):.for i in range(len(a_list)):, reading both at position i.len(marks).max([]) or sum-then-divide on an empty list. An empty list gives an error (max) or a division by zero. Check len(a_list) > 0 first.append. squares + [n * n] does not change squares. Use squares.append(n * n).IndexError.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
for item in a_list: goes through the items.sum(), max(), min() and len() for quick answers.if. Build with [] and append.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
sum([2, 4, 6])?max([5, 9, 7]) - min([5, 9, 7])?marks?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.