User Guide
Table Of Contents
136
However, most things in Python are objects. You will learn more
about these in section 6.6 Classes and Objects on page144.
Using Lists and Dictionaries
Lists collect items together into a single variable. They are
ordered – each slot in the list is given a number starting at zero.
To create a list, use square brackets. And then each item in the
list is accessed using square brackets and the item number:
Beatles = ["John", "Paul", "Pete", "George"]
print(Beatles[0])
The items in a list can be changed:
Beatles[2] = "Ringo"
Lists are useful when you do not want to give each item a
separate variable name, or when the amount of data that you
have changes when the program is running.
You can find the length of a list using the function len(). For
example, len(Beatles) gives the result 4.
To delete an item from a list, use del(). When an item is deleted,
all of the items that follow it move up one position. So, in this
example, deleting the first item makes “Paul” the new first item.
“Ringo” would then be second item, and “George” third.
There are also several useful “methods” that you access using a
dot after the variable name. For example:
Beatles.reverse()
Method Description
append(obj) Adds the specified item to the end of the list.
count(obj) Counts how many times the specified item
appears in the list.
index(obj) Searches the list for the specified item and returns
its position in the list.