Loops, and where your data lives

INPUT · Slides

Counting how many

01 / 06

You want to know how many

Once you are adding with append and taking away with pop, you lose track of how many are in there.

You could count them with a for, but four lines for that is a waste. Python has a tool for counting built in.

02 / 06

len counts them

Hand a list to len (short for length) and the number of things in it comes back.

It is the same shape as print — you hand it something inside the brackets.

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

Result

3

03 / 06

An empty list is 0

A list with nothing in it has length 0. No error.

So if len(fruits) == 0: picks out "there is nothing here". Showing something different when there is no data is a job that comes up in every real app.

fruits = []print(len(fruits))if len(fruits) == 0:    print("empty")

Result

0
empty

04 / 06

The last number is one less than len

A list of three is numbered 0, 1, 2. So the last number is len take one.

Get that wrong and you get an IndexError. The count and the last number are always one apart — say it out loud and it will stick.

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

Result

3
grape

05 / 06

range(len(xs)) loops over the numbers

Put len and range together and you can loop over the numbers instead.

Remember that range(3) gives 0, 1, 2. So range(len(fruits)) gives exactly the numbers that list has.

If you only want the contents, plain for fruit in fruits: is better. You reach for this shape when you need the number itself.

fruits = ["apple", "orange", "grape"]for i in range(len(fruits)):    print(i, fruits[i])

Result

0 apple
1 orange
2 grape

06 / 06

len works on text too

len is not only for lists. Hand it text and you get the number of characters.

Python is built so that things in a row can be handled with the same tools. What you learned on lists works on text — and that is what the next group is about.

print(len("hello"))print(len(["apple", "orange"]))

Result

5
2