Database Reference
In-Depth Information
Lists
Lists are a common way to store an indexed group of values within an object. A simple list is assigned to an object
in a similar way to how a string is assigned to an object, the difference being that the object is now a list object, not a
string object. The significance of this is not as great in Python as in other languages, but it is a good idea to have an
understanding that there is a difference that can potentially have an impact on the behavior of a program.
This example shows a list object with a single value. The values assigned to a list are encapsulated by brackets.
Without the brackets this would be a simple string object. See here:
>>> mylist = ['one']
>>> print(mylist)
['one']
>>> type(mylist)
<type 'list'>
>>> mystring = 'one'
>>> type(mystring)
<type 'str'>
Simple Lists
A list with a single value can be useful, but the purpose of lists is to be able to assign multiple list values within a
single object. These values are referred to as elements . In the previous example, a value of one was assigned as the first
element in the mylist object.
This example creates a list called mylist with five members. Printing the list displays it exactly how it was created.
The five elements are printed within an opening and closing bracket. The brackets are what tell us that this is a list and
not a string or any other type of object. A list index of 2 is actually the third element in the list since the index numbers
start at 0.
The power of lists comes from the plethora of ways that the individual elements can be manipulated. For
example, any element can be queried from a list by specifying its index number. The index of a list starts at zero, so the
first element of a list is assigned the number zero:
>>> mylist = ['one', 'two', 'three', 'four', 'five']
>>> print(mylist)
['one', 'two', 'three', 'four', 'five']
>>> type(mylist)
<type 'list'>
>>> print(mylist[2])
three
A list is mutable, which means it can be manipulated after it has been created. It can be lengthened or shortened,
and the elements can be changed. This example shows the mylist object being appended with the value of 6 . The
number of elements in this object goes from five to six:
>>> mylist.append('six')
>>> print(mylist)
['one', 'two', 'three', 'four', 'five', 'six']
>>> print(len(mylist))
6
The len() function used in the previous example displays the number of elements in the list. Like many
functions, len() can be used on lists, strings, and all other object types.
 
Search WWH ::




Custom Search