Loops, and where your data lives

INPUT · Slides

Taking characters out by number

01 / 07

Strings come out by number as well

A list handed you one item at a time with fruits[0].

As it turns out, a string takes exactly the same writing. Write name[0] and you get the first character.

name = "Noah"print(name[0])

Result

N

02 / 07

The numbers start at zero

As with lists, the numbers start at 0. The first character is 0, the second is 1.

letterNoah
index0123

"The first one is zero" throws everybody the first time. You have been down this road once with lists, so treat it as the same idea, used again.

name = "Noah"print(name[1])print(name[3])

Result

o
h

03 / 07

Minus counts from the back

The minus numbers you could use on a list still work. [-1] is the last character, [-2] the one before it.

You get the last character without counting the length first, which is very useful indeed.

name = "Noah"print(name[-1])print(name[-2])

Result

h
a

04 / 07

len measures the length too

len, which counted the items in a list, gives you the number of characters when you hand it a string.

Everything in there counts as one: letters, digits, spaces, punctuation. To len they are all simply one more thing in the row.

name = "Noah"print(len(name))

Result

4

05 / 07

Ask for a number that is not there

A four-character string has no [4]. The numbers run from 0 to 3, and that is the lot.

Point at one that does not exist and Python stops with an error.

name = "Noah"print(name[4])

Result

IndexError: string index out of range

06 / 07

What comes out is a string as well

The single character name[0] gives you is a string in its own right. So you can join it with + or repeat it with *.

Out of a string comes a string. Same reasoning as a list handing you back one of its items.

name = "Noah"print(name[0] + name[-1])

Result

Nh

07 / 07

One character at a time

Put range and len together and you make the numbers from 0 upwards, which takes the characters out one by one.

That is the moment looping and indexing meet. Next lesson takes several characters at once rather than one.

name = "Amy"for i in range(len(name)):    print(name[i])

Result

A
m
y