Flylib.com

Books Software

 
 
 

Section 2.8. Lists and Tuples


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.



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 numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dicts are enclosed by curly braces ( { } ).

>>> 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 Indentation

Code 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 generally prefer to avoid change, so perhaps after many years of coding with brace delimitation, the first impression of using pure indentation may not be completely positive. However, recall that two of Python's features are that it is simplistic in nature and easy to read. If you have a strong dislike of indentation as a delimitation *** , we invite you to revisit this notion half a year from now. More than likely, you will have discovered that life without braces is not as bad as you had originally thought.



2.11. if Statement

The standard if conditional statement follows this syntax:


if


expression:
   if_suite


If the expression is non-zero or TRue , then the statement if_suite is executed; otherwise , execution continues on the first statement after. Suite is the term used in Python to refer to a sub-block of code and can consist of single or multiple statements. You will notice that parentheses are not required in if statements as they are in other languages.


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 strange and/or distracting at first, but a set of if-elif-else statements are not as "ugly" because of Python's clean syntax. If you really want to circumvent a set of chained if-elif-else statements, another elegant workaround is using a for loop (see Section 2.13) to iterate through your list of possible "cases."

You can learn more about if , elif , and else statements in the conditional section of Chapter 8.