Loops, and where your data lives

INPUT · Slides

Swapping the contents around

01 / 07

A list can change after you make it

Part of what makes a list useful is that you can change what is inside it later.

Add something to a shopping list, cross off what is done, correct a mistake. Those everyday moves go straight into code.

02 / 07

Name a number and write over it

Put the taking-out on the left of an = and it becomes writing-over.

fruits[0] = "peach" swaps the one at 0 for peach. If you can take one out, there is almost nothing new here.

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

Result

['peach', 'orange', 'grape']

03 / 07

append puts one on the end

To add to the contents you use append, which means "add to the end".

You write fruits.append("peach") — a dot after the name of the list, which is a shape you have not seen yet. What you add goes right at the back.

fruits = ["apple", "orange"]fruits.append("peach")print(fruits)

Result

['apple', 'orange', 'peach']

04 / 07

Grow a list from empty

append really earns its keep when you start with an empty list and fill it in a for.

Set up [] first, then add one thing per turn. You will write this shape more times than you can count, so get your hands on it now.

numbers = []for i in range(4):    numbers.append(i * i)print(numbers)

Result

[0, 1, 4, 9]

05 / 07

remove names the thing itself

There are two ways to take something out. The first is remove, where you name the thing you want gone.

Two warnings. If the same thing is in twice, only the first goes, and asking to remove something that is not there is an error.

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

Result

['apple', 'grape']

06 / 07

pop names the number

The second is pop, which takes a number. pop(0) for the front, and nothing at all for the last.

What sets it apart from remove is that it hands the thing back to you. Read it as "take it out and keep it" rather than "get rid of it".

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

Result

grape
['apple', 'orange']

07 / 07

In short

  • fruits[0] = "peach" … name a number and write over it
  • fruits.append("peach") … add to the end
  • fruits.remove("orange") … name the thing and take it out
  • fruits.pop() … name a number and take it out. Nothing means the last

Once things are going in and out, how many there are now starts to matter. That is next.