Loops, and where your data lives

INPUT · Slides

Lining values up in a list

01 / 06

One variable each is not enough

You want to remember three fruits. With what you have so far, that means three variables.

What about thirty? Or three hundred? Every extra value costs you another line. No real app gets built that way.

fruit1 = "apple"fruit2 = "orange"fruit3 = "grape"print(fruit1)

Result

apple

02 / 06

Line them up inside [ ]

A list — a container that holds values in order — brings you down to one name however many there are.

You write it by putting the values inside square brackets [ ], separated by commas. Drop that into a variable and the whole lot answers to a single name.

fruits = ["apple", "orange", "grape"]print(fruits)

Result

['apple', 'orange', 'grape']

03 / 06

Numbers go in too

Text is not the only thing a list holds. Numbers work the same.

The usual practice is to put things of one kind in one list — a list of scores, a list of prices, a list of names. Keep to that and working on them together stays easy.

scores = [80, 95, 60]print(scores)

Result

[80, 95, 60]

04 / 06

An empty list is allowed

Write [] and you get a list with nothing in it.

It is common to set one up empty first, as the container you are about to fill. Filling it comes a little after the next lesson, so for now just look at the shape.

fruits = []print(fruits)

Result

[]

05 / 06

Take them out one at a time with for

Here is the satisfying part. A list goes straight into a for.

Write for fruit in fruits: and the contents arrive in fruit in order from the front. Three items or three hundred, the code stays the same three lines.

fruits = ["apple", "orange", "grape"]for fruit in fruits:    print(fruit)

Result

apple
orange
grape

06 / 06

Lists and for go together

A list holds things together; for takes them out one at a time. Treat the two as a pair.

  • make a list … fruits = ["apple", "orange"]
  • see the whole thing … print(fruits)
  • see them one at a time … for fruit in fruits:

Next you learn how to ask for just the third one. Name a number and you can grab one without looping over everything.