Lists in PY Games

Updated: February 17, 2022
No Credit Card Required


Welcome to the fourth lesson of Python game development, we're going to introduce an important concept, Lists. Exciting right?.

A LIST is used to store data. When you want to store a lot of data or order the data, you're going to need to use a List. A List can hold many Items together and keep them in order. Python gives each Item a number that shows its position in the List, you can change the Items in the List at any time.

All right, go to Replit and create a new Repl and name it PGD_4_Lists.

Imagine you are writing a multiplayer game and and you want to store the names of the players in each team, you could create a variable for each player, which might look similar to the example below. There are six different variables here, and you need to assign them six different values. That's a lot of work.

There must be a better way to update and manage so many variables. Well, there is because you could use a List. Because the List is ordered, the Items have a defined position in the List. We call the position in that order the Index. The first Item in the List is in the position zero, then one, then two, three, and so on. Once your data is in a List, it's much easier to work with.

But how do you get an Item out of the List? It's pretty easy in Python. To get an Item out of the List, just type the name of the List, then add the Items position or Index in the List by putting it inside square brackets.

Oh, what? No, uh, we added position square brackets 1, so it should display “coconut”. Did I make a mistake? No. Python Index starts counting List Items from zero rather than starting at one. So fruits position 1 will return “banana”. And then if we want the last Item from the List, it would look like fruits 2.

So here we have this long List of all the fruit available in our fruit direct online store. But we need to change one of the Items as it's no longer available. How can we do that? It's pretty simple. To change the value of a specific Item refer to the Index number. The statement fruits 1 equals cheery updates Item 1 in the List with the new string “cherry”.

Now sometimes in a really long List, you may only want to display the value of Items within a specific range and not the complete List. To display the value of Items within a specific range like “apple”, “banana” etc. refer to the range of Index numbers for the Items you want to display.

So “print List 2 to 5” would display the Items in positions 2 to 5 in the List. Methods are used to change the List. Well, there are a number of Methods available to use a program they all follow kind of the same syntax, the List name followed by the Method you're calling like this.

Cool. You are making great progress and your coding toolkit is currently expanding. So I'll see you again soon.