Graphics Reference
In-Depth Information
>>> ['a','b','c'][0]
'a'
>>> ['a','b','c'][1]
'b'
>>> ['a','b','c'][2]
'c'
IndexaccesstolistsinPythonisverypowerful.Youcanreturnnotjustindividual elements butalso slices or
sublists , by indicating the start index and the index to which you want the sublist to extend (noninclusively). In
this example, the [1:4] indexes are called, which returns the sublist extending from index 0 to index 3 of the
original list:
>>> ['a','b','c','d','e'][1:4]
['b', 'c', 'd']
>>>
Twoimportantmethodsdefinedforlistsare append() and extend() .Bothaddelementstolists.Insome
cases, these methods can be used interchangeably, but the way they are used is different. The first method, ap-
pend() , adds a single element to a list. The append() method changes the list in place and does not, itself,
output anything. To see how the list has changed, you need to pass it to a variable as follows so you can print
the value after changing it:
>>> mylist = ['a','b','c']
>>> mylist.append('d')
>>> mylist
['a', 'b', 'c', 'd']
The other common way to add elements to lists is to add the entire contents of another list to the first list,
which is done using extend() as shown here:
>>> mylist = ['a','b','c']
>>> mylist.extend(['d','e','f'])
>>> mylist
['a', 'b', 'c', 'd', 'e', 'f']
In this case, the argument for extend() is itself a list, and the resulting list is the concatenation of the
original list with the contents of extend() . Note that if append() is called with a list as an argument, the
effect is quite different:
>>> mylist = ['a','b','c']
>>> mylist.append(['d','e','f'])
>>> mylist
['a', 'b', 'c', ['d', 'e', 'f']]
If append() is used with a list argument, the entire new list is appended as a single element in the original
list. In this example, the new, post-append list has four elements, the last of which is itself a list.
Tuples are similar to lists in many respects. Instead of using square brackets, they are identified by round
brackets. Their elements can be accessed by index similarly to the way lists can be. Tuples cannot be appended
to or extended, and you cannot assign new values to individual items in tuples. For this reason, tuples are suit-
able only for collections that are fixed at the time of their creation.
Search WWH ::




Custom Search