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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access