< Prev  |  Home  |  Next >

Python Lists

We’ve learnt that a string is basically an array of characters in a single variable, that can be accessed individually, or in groups, by using an index. But it’s not just characters that can be accessed in an array. Whole strings, integers or floating point numbers can also be used in this way, by putting them in a list.

Here’s a fascinating example:

A list is just a collection of values in square brackets, each value separated by a comma. We still use speech marks (or single quotes) to represent strings, so “4″ in the list above is actually a string, not an integer.

We can access values in the list just like we did in an array in the previous section:

Notice how in lines 6 and 7 we even used an array twice, Once to find shopping list item 3 (array position 2), and then again to find some characters within the list item found. This is a two-dimensional array. You can also add and remove from lists, as you can see in lines 8 and 10.

We can use variables to store array position numbers, which means we can do anything with the array position that we can do with any other variable. Here’s a program to generate poetry:

This program produces such moving poems as:

Fear, like a heartache near my face
...You're welcome.

So deep.

Even though each part of the poem has 4 possible choices, why did we write:

when we could have just written:

At the moment, they both do the same thing. They both pick a random number between 0 and 3 (to choose one of the four possible parts). The first method does this by finding the length of the list (4) and then subtracting 1 (to get 3). Isn’t that just a long way of doing something simple? Well, yes it is. But what if we add more text options to each part of the poem, like this:

Now the easy way doesn’t work properly, unless we change the first random number generator to be extended to take the newly added words into account:

…but the other way would still work:

It would take the length of the list (now 6) and subtract 1 (giving a random number between 0 and 5). This is called future-proofing, meaning that the code doesn’t need to be changed in the future if other parts of our program change. Programming like this will save you a lot of time, and stop your whole program from breaking because you’ve added something small.


Write a program to store items in an inventory for an RPG computer game. Your character can add items (like swords, shields and various potions) to their inventory, as well as ‘use’ an item, that will remove it from the inventory list.

You could even have other variables like ‘health’ and ‘strength’, that are affected by ‘finding’ or ‘using’ items in the inventory.

< Prev  |  Home  |  Next >