01 / 07
Loops, and where your data lives
INPUT · Slides
Taking things out of a row
02 / 07
Values in a row, held as one
There is a way of writing several values in order and holding them together. Wrap them in square brackets and separate them with commas, and that is all there is to it. It is called a list.
Show it as it is and out it comes in the shape you wrote. The order you wrote stays put — that is what a list is for.
fruits = ["apple", "orange", "grape"]print(fruits)Result
['apple', 'orange', 'grape']
03 / 07
Taking them out one at a time with for
Put a list after in and the contents arrive in the variable one at a time.
On the first go "apple" is in fruit, on the second "orange", on the third "grape". It ends when the contents run out, so there is no counting to do.
fruits = ["apple", "orange", "grape"]for fruit in fruits: print(fruit)Result
apple orange grape
04 / 07
How to name them
You can also write the list straight after in without giving it a variable. For a short one that reads better.
There is a knack to the names. The one holding them all is plural, the one receiving them singular. Line up fruits and fruit like that and the code starts to read like English.
for colour in ["red", "blue"]: print(colour)Result
red blue
05 / 07
Lists of numbers work too
It is not only text that goes in a list. Numbers are fine as well.
Set the container up outside, add into it inside. The shape you learned with range carries straight over.
scores = [60, 80, 100]total = 0for score in scores: total += scoreprint(total)Result
240
06 / 07
It is the same shape as range
for i in range(3): and for fruit in fruits: are exactly the same shape. All that changed is what sits after in.
In truth, Python's for was always the writing for "take the things in a row, one at a time". Even range(3) is making "a row containing 0, 1 and 2". Counting is the side effect, not the other way round.
07 / 07
There is far more a list can do
For now, making one and taking things out one at a time is quite enough.
"Take out only the third one", "add one on later", "count how many are in there" — the tools for all of that exist, but they come together in the group straight after this one.
Until then, write with nothing but going through it from the front with for. Even that opens up a great deal.