Making Lists

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.


Creating a List

Create a new Repl 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 [].

A list is made of items surrounded by suare brackets. If a list has more than one item, those items are separated by commas:

list_name = [item1, item2, item3, etc..]


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.


Challenge

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?

Activity

To get more practice with lists, you're now going to create a to-do list. Create a variable called todo and set it equal to a list of tasks (do homework, walk the dog, eat, etc.). The list should have AT LEAST 5 ITEMS. After you create your list, print the following:

  • The length of the list
  • The first item in the list
  • The fifth item in the list
For more practice with variables and lists, try out THIS activity and test your knowledge!

Copyright © KX Technology Group, LLC. All Rights Reserved.