Want to keep learning?

This content is taken from the Raspberry Pi Foundation & National Centre for Computing Education's online course, Programming 102: Think Like a Computer Scientist. Join the course to learn more.

Strings as lists

Although they may not look the same, in Python we can treat strings in a very similar way to lists. In Python terms, they are both “iterables”. This means that, in much the same way as we can use a for loop to repeat an action for each element in a list, we can do the same for each character in a string:

my_list = ['apple', 'banana', 'pear']
my_string = 'fig'

for item in my_list:
for item in my_string:

The code inside each of these loops will run three times, as the list has three elements, and the string has three characters.

We can also access characters in strings in the same way as elements in lists, using indices inside square brackets. For example, for the string topic = "algorithms", topic[0] would refer to the first character, which in this case is "a". topic[1] would give "l", topic[2] would give "g", and so on. As with lists, you can use negative numbers to count back from the end of the list: topic[-1] would give "s", while topic[-5] would give "i".

Slicing strings also works in the same way as slicing lists. Try out the following code:

topic = "slicing strings"


What strings are printed in each case?

Check that you are happy with how this works. The number before the colon gives the index of the first character in the slice, while the number after the colon gives the index of the first character which will not be included in the slice. Also, the space between the two words counts as a character, and in this string its location gives an index of 7.

Here is an example of a list of team names:


On scoreboards, sports teams are sometimes referred to using a contraction of their name, often the first three letters. Can you write some code in order to create a new list, teams_short, containing three-letter contractions of each of the teams in the list, in the same order as they appear in teams?

Share your code, problems, and suggestions in the comments.

Share this article:

This article is from the free online course:

Programming 102: Think Like a Computer Scientist

Raspberry Pi Foundation