2.8. Lists and TuplesLists 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
>>> 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. |
2.9. Dictionaries
Dictionaries (or "dicts" for short) are Python's mapping type and work like associative arrays or hashes found in Perl; they are made up of key-value pairs. Keys can be almost any Python type, but are usually
>>> aDict = {'host': 'earth'} # create dict
>>> aDict['port'] = 80 # add to dict
>>> aDict
{'host': 'earth', 'port': 80}
>>> aDict.keys()
['host', 'port']
>>> aDict['host']
'earth'
>>>
for
key
in
aDict:
...
print
key, aDict[key]
...
host earth
port 80
Dictionaries are covered in Chapter 7. |
2.10. Code Blocks Use IndentationCode blocks are identified by indentation rather than using symbols like curly braces. Without extra symbols, programs are easier to read. Also, indentation clearly identifies which block of code a statement belongs to. Of course, code blocks can consist of single statements, too.
When one is new to Python, indentation may comes as a surprise. Humans
|
2.11. if Statement
The standard
if
conditional statement
if expression: if_suite
If the
expression
is
if x < .0: print '"x" must be atleast 0!' Python supports an else statement that is used with if in the following manner:
if expression: if_suite else : else_suite Python has an "else-if" spelled as elif with the following syntax:
if expression1: if_suite elif expression2: elif_suite else: else_suite
At the time of this writing, there has been some discussion pertaining to a
switch
or
case
statement, but nothing concrete. It is possible that we will see such an animal in a future version of the language. This may also seem
You can learn more about if , elif , and else statements in the conditional section of Chapter 8. |