Tuples
A tuple is a sequence of arbitrary objects separated by commas and enclosed in parentheses. If the tuple contains a single object, the parentheses may be omitted. Tuples support the same operations as strings; they are also immutable.
>>> rec = (’Smith’,’John’,(6,23,68)) # This is a tuple
>>> lastName,firstName,birthdate = rec # Unpacking the tuple
>>> print firstName
John
>>> birthYear = birthdate[2]
>>> print birthYear
68
>>> name = rec[1] + ’ ’ + rec[0]
>>> print name
John Smith
>>> print rec[0:2]
(’Smith’, ’John’)
Lists
A list is similar to a tuple, but it is mutable, so that its elements and length can be changed.Alist is identified by enclosing it in brackets.Here is a sampling of operations that can be performed on lists:
>>> a = [1.0, 2.0, 3.0] # Create a list
>>> a.append(4.0) # Append 4.0 to list
>>> print a
[1.0, 2.0, 3.0, 4.0]
>>> a.insert(0,0.0) # Insert 0.0 in position 0
>>> print a
[0.0, 1.0, 2.0, 3.0, 4.0]
>>> print len(a) # Determine length of list
5
>>> a[2:4] = [1.0, 1.0] # Modify selected elements
>>> print a
[0.0, 1.0, 1.0, 1.0, 1.0, 4.0]
If a is a mutable object, such as a list, the assignment statementb = adoes not result in a new object b, but simply creates a new reference to a. Thus any changes made to b will be reflected in a. To create an independent copy of a list a, use the statement c = a[:], as illustrated below.
>>> a = [1.0, 2.0, 3.0]
>>> b = a # ’b’ is an alias of ’a’
>>> b[0] = 5.0 # Change ’b’
>>> print a
[5.0, 2.0, 3.0] # The change is reflected in ’a’
>>> c = a[:] # ’c’ is an independent copy of ’a’
>>> c[0] = 1.0 # Change ’c’
>>> print a
[5.0, 2.0, 3.0] # ’a’ is not affected by the change
Matrices can represented as nested lists with each row being an element of the list. Here is a 3 × 3 matrix a in the formof a list:
>>> a = [[1, 2, 3], \
[4, 5, 6], \
[7, 8, 9]]
>>> print a[1] # Print second row (element 1)
[4, 5, 6]
>>> print a[1][2] # Print third element of second row
6
Reading Input
A convenient way to input a number and assign it to the variable a is
a = eval(raw input(prompt))
Printing Output
The modulo operator (%) can be used to format a tuple. The formof the conversion statement is
’%format1 %format2 · · ·’ % tuple
>>> a = 1234.56789
>>> n = 9876
>>> print ’%7.2f’ % a
1234.57
>>> print ’n = %6d’ % n # Pad with 2 spaces
n = 9876
>>> print ’n = %06d’ %n # Pad with 2 zeroes
n = 009876
>>> print ’%12.4e %6d’ % (a,n)
1.2346e+003 9876