0% found this document useful (0 votes)
7 views1 page

Coding Projects in Python (Dragged) 6

Uploaded by

Hayley Kelsey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Coding Projects in Python (Dragged) 6

Uploaded by

Hayley Kelsey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

VA R I A B L E S 27

Lists
When you want to store a lot of data, or
perhaps the order of the data is important,
you may 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.

1 Multiple variables
Imagine you’re writing a multiplayer game
>>> rockets_player_1 = 'Rory'
>>> rockets_player_2 = 'Rav'
and want to store the names of the players
in each team. You could create a variable for >>> rockets_player_3 = 'Rachel'
each player, which might look like this...
>>> planets_player_1 = 'Peter'
>>> planets_player_2 = 'Pablo'
With three players per team, >>> planets_player_3 = 'Polly'
you’d need six variables.

2 Put a list in a variable


...but what if there were six players per team?
>>> rockets_players = ['Rory', 'Rav',
Managing and updating so many variables 'Rachel', 'Renata', 'Ryan', 'Ruby']
would be difficult. It would be better to use a >>> planets_players = ['Peter', 'Pablo',
list. To create a list, you surround the items you
want to store with square brackets. Try out 'Polly', 'Penny', 'Paula', 'Patrick']
these lists in the shell.
This list is stored in the
variable planets_players.

The list items must be


separated by commas. This line gets the first item
in the list, from position 0.

3 Getting items from a list


Once your data is in a list, it’s easy to work with.
>>> rockets_players[0]

To get an item out of a list, first type the name 'Rory'


of the list. Then add the item’s position in the >>> planets_players[5]
list, putting it inside square brackets. Be careful:
Python starts counting list items from 0 rather 'Patrick'
than 1. Now try getting different players’ names
This line gets the last item
out of your team lists. The first player is at
in the list, from position 5.
position 0, while the last player is at position 5.

Hit enter/return to
retrieve the item.

You might also like