11/4/13

Tuples


In [2]:
t = (1,2)
type(t)


Out[2]:
tuple

In [4]:
t = tuple()
type(t)


Out[4]:
tuple

In [5]:
t = tuple('test')
print t


('t', 'e', 's', 't')

In [6]:
l = list()
l.append(5)
l.append(6)
t = tuple(l)
print t


(5, 6)

In [7]:
t = tuple( range(10) )
print t


(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

In [8]:
print (5)
print (5,)


5
(5,)

In [9]:
print (5+3)
print (5+3,)


8
(8,)

In [10]:
print type( (5) )
print type( (5,) )


<type 'int'>
<type 'tuple'>

In [11]:
print [5]
print [5,]


[5]
[5]

Tuple assignment

Assign multiple values to multiple variables at once


In [12]:
print range(2)


[0, 1]

In [13]:
a, b = range(2)
print a
print b


0
1

In [14]:
a,b,c = range(2)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-ad09d1e96dc0> in <module>()
----> 1 a,b,c = range(2)

ValueError: need more than 2 values to unpack

In [15]:
d = {1:2,2:3,3:4}
print d.keys()
print d.values()
print d.items()


[1, 2, 3]
[2, 3, 4]
[(1, 2), (2, 3), (3, 4)]

In [17]:
for key in d:
    print key


1
2
3

In [18]:
for value in d.values():
    print value


2
3
4

In [20]:
for items in d.items():
    print items


(1, 2)
(2, 3)
(3, 4)

In [22]:
for key, value in d.items():
    print "key:", key
    print "value:", value


key: 1
value: 2
key: 2
value: 3
key: 3
value: 4

multiple return values


In [23]:
div = 7 / 3
rem = 7 % 3
print "div:",div
print "rem:",rem


div: 2
rem: 1

In [24]:
div, rem = divmod(7,3)
print "div:",div
print "rem:",rem


div: 2
rem: 1

multiple arguments


In [26]:
def addall(*nums):
    total = 0
    for n in nums:
        total = total + n
    return total
print addall(1,2,3,5)


11

In [30]:
t = (7,3)
print divmod(*t)


(2, 1)

zip builtin

combines multiple sequences into a list of tuples


In [31]:
word = "frog"
nums = [1,2,3,4]
print zip(word,nums)


[('f', 1), ('r', 2), ('o', 3), ('g', 4)]

creating dictionaries with tuples


In [32]:
d = dict( zip(word,nums) )
print d


{'r': 2, 'g': 4, 'o': 3, 'f': 1}

updating/expanding dictionaries


In [36]:
d.update( [ ('b',2), ('f', 4) ] )
print d


{'a': 4, 'b': 2, 'e': 3, 'g': 4, 'f': 4, 'o': 3, 'r': 2}

tuple assignment in for loops


In [34]:
l = [1,2,3,4,5]
for i in range( len(l) ):
    print i, l[i]

print ""

for i,val in enumerate(l):
    print i,val


0 1
1 2
2 3
3 4
4 5

0 1
1 2
2 3
3 4
4 5

In [33]: