You might be thinking …
That’s OK. An iterable is just something which can be “iterated”, or stepped through one bit at a time, such as a list of numbers or words. Before delving into the subject of iteration in Python, we will take some time to explore iterables and how they work.
Though you may not have realised it, you have already used an iterable during this course: a string.
Conceptually a string is a list of characters in an order: for example, “hello” is a list of 5 characters in the order “h” “e” “l” “l” “o”.
Understanding how lists and iterables work is important because this is how Python iterates: by running the same code for each item in a list.
First let’s explore the strings as iterables in the REPL to see how they work.
- Open the REPL (or console in Trinket).
- Create a string variable called
phraseand assign it the value
"hello", by typing the following into the REPL and pressing Enter.
phrase = "hello"
You can access individual elements (or items) in a list or split them up into parts by using indices, an index being a position in a list.
hello has 5 characters, the first element being
h which has an index of
0, the second element
e has an index of
1 and so on:
0 1 2 3 4 h e l l o
Tip: It’s a controversial subject, but the majority of computer programmers agree that indices should start at
0 and not
1, so it’s a good idea to embrace the idea that numbers start at zero!
You access elements in a list by using square brackets
 after the variable name, adding the index of the element you wish to get:
- Get the first character from your string variable by entering this into the REPL.
Challenge: repeat the step above, changing the index to get the fourth character (“l”) in the string.
Indices don’t have to be positive numbers. You can also use negative indices to get elements from the end of the list. E.g. the last element in a list would have the index of
-5 -4 -3 -2 -1 h e l l o
- Get the last character from your string using the REPL.
What do you think the advantage is of using
phrase[-1] over using
phrase to get the last element? Put your thoughts in the comments.