A List is used to store a collection of data. It can hold many different values and keep them in order. For example, a list can store a deck of cards for a game, such as Poker, so the code knows which card to deal next. The position of each value in the list is identified with a number, starting from 0. You can use these numbers to change list values.
Create a new file called list_example.
Now imagine you’re coding a multiplayer game
and want to have a different variable for
each card. You would need 52 variables to
store a whole deck of cards, but we’ll just
work with five for now.
That's still a lot of variables to keep track of, though. What if we could store multiple values in one variable?
There is where lists come into play! To create a list, surround the
values you want to store with square brackets [].
It’s easy to work with a list once you have
all your values in it. To get an item from a
list, type the name of the list, followed by
the item’s position in the list within square
parentheses. But watch out—in Python, the
first position in a list is 0, not 1. Now try
getting different cards out of your cards list.
Type the following code and run your program. What do you get as the output?
Play around with the above code. change the numbers in the square brackets, change the data in the cards variable.
For some programs, it’s useful to be able to count
the number of items in a list. You can do
this using the len() function from last lesson.
To find out the number of characters in the list cards, type this line of code into the shell
after you’ve created the list, then hit run the code. What do you think the output will be?
Copyright © KX Technology Group, LLC. All Rights Reserved.