- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
2.8 Lists and Tuples
Lists and tuples can be thought of as generic “arrays” with which to hold an arbitrary number of arbitrary Python objects. The items are ordered and accessed via index offsets, similar to arrays, except that lists and tuples can store different types of objects.
There are a few main differences between lists and tuples. Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed. Tuples are enclosed in parentheses ( ( ) ) and cannot be updated (although their contents may be). Tuples can be thought of for now as “read-only” lists. Subsets can be taken with the slice operator ( [] and [ : ] ) in the same manner as strings.
>>> aList = [1, 2, 3, 4] >>> aList [1, 2, 3, 4] >>> aList[0] 1 >>> aList[2:] [3, 4] >>> aList[:3] [1, 2, 3] >>> aList[1] = 5 >>> aList [1, 5, 3, 4]
Slice access to a tuple is similar, except it cannot be modified:
>>> aTuple = ('robots', 77, 93, 'try') >>> aTuple ('robots', 77, 93, 'try') >>> aTuple[:3] ('robots', 77, 93) >>> aTuple[1] = 5 Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment
You can find out a lot more about lists and tuples along with strings in Chapter 6.