pop() # Return and remove the last element
'The Boss'
>>> stacklist.pop()
'Catbert'
Chapter 6: Programming Survival Skills
143
PART III
>>> stacklist.pop()
'Dogbert'
>>> stacklist
['Dilbert']
>>> stacklist.extend(['Alice', 'Carol', 'Tina'])
>>> stacklist
['Dilbert', 'Alice', 'Carol', 'Tina']
>>> stacklist.reverse()
>>> stacklist
['Tina', 'Carol', 'Alice', 'Dilbert']
>>> del stacklist[1] # Remove the element at index 1
>>> stacklist
['Tina', 'Alice', 'Dilbert']
Next we??™ll take a quick look at dictionaries, then files, and then we??™ll put all the
elements together.
Dictionaries
Dictionaries are similar to lists except that objects stored in a dictionary are referenced
by a key, not by the index of the object. This turns out to be a very convenient mechanism
to store and retrieve data. Dictionaries are created by adding { and } around a keyvalue
pair, like this:
>>> d = { 'hero' : 'Dilbert' }
>>> d['hero']
'Dilbert'
>>> 'hero' in d
True
>>> 'Dilbert' in d # Dictionaries are indexed by key, not value
False
>>> d.keys() # keys() returns a list of all objects used as keys
['hero']
>>> d.values() # values() returns a list of all objects used as values
['Dilbert']
>>> d['hero'] = 'Dogbert'
>>> d
{'hero': 'Dogbert'}
>>> d['buddy'] = 'Wally'
>>> d['pets'] = 2 # You can store any type of object, not just strings
>>> d
{'hero': 'Dogbert', 'buddy': 'Wally', 'pets': 2}
We??™ll use dictionaries more in the next section as well.
Pages:
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307