- This may sound complicated, but lists within lists are the best way to save ‘records’ i.e. multiple bits of information about one thing, such as the name, address and telephone number of a user
- This type of list is known as a two-dimensional list
- Lists are sometimes referred to as ‘arrays’
#Create a new list, each list item containing two values
users = [
["Mike","Smith",24],
["John","Thompson",56],
["Mary","Field",19]
]
#Add additional record
users.append(["Katie","Johnson",15])
#Use elements in for loop ([0] is name, [1] is surname, [2] is age)
for user in users:
print(user[0],user[1],user[2])
#Display a specific item (this example will display '56'
print(users[1][2])
#Access individual parts of each item (change a record)
#Indexes work down, then across
users[0][0] = "Michael"
users[0][1] = "Thomas"
#Messy, but quick method of printing an entire list
print(users)
Index | 0 | 1 | 2 |
---|---|---|---|
0 | Mike | Smith | 24 |
1 | John | Thompson | 56 |
2 | Mary | Field | 19 |
Tasks
- Type in the code and make sure it works
- Add a new field to the list items to hold the e-mail address of each person, and show you can print and edit it
- Save and label your code
Extension Task
Creating code to neatly print out a list is important. Use a for loop and appropriate escape characters (\n) or (\t) to display the list as a table. There are several ways to do this, the most efficient using two FOR loops, one inside the other