O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Lists and Tuples

Much of Python’s power comes from its support for lists and its compact syntax for manipulating them. Lists are wrapped in square brackets and can contain any Python objects. You can also insert and delete items in a list and even use negative positions to access the end of the list without knowing its length:

>>> mylunch = ['spam','eggs', 'guinness','raspberries','wafer-thin mint']
>>> mylunch[0]
'spam'
>>> mylunch[1:3], mylunch[-1]
(['eggs', 'guinness'], 'wafer-thin mint')
>>>

When you enter two results separated by a comma on the same line, you get two expressions, but enclosed in parentheses. Parentheses indicate a tuple , which is similar to a list but can’t be modified once created:

>>> mylunch[2] = 'tea'
>>> mylunch
['spam', 'eggs', 'tea', 'raspberries', 'wafer-thin mint']
>>> meal_deal = ('burger','fries','coke')   # a tuple
>>> meal_deal[1] = 'onion rings'
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
TypeError: object doesn't support item assignment
>>>

The last example also shows our first error message. When errors occur, you see a traceback stating which functions were active and the line of the source file that caused the error, as well as the error type and message on the last line. In this case, you type commands interactively rather than running a source file, so you don’t see a helpful filename or line number.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required