Python Tuples

In [1]:
friend_list = ['Ahmed', 'Ali', 'Samer'] # list 
In [2]:
friend_list[1]
Out[2]:
'Ali'
In [3]:
friend_tuple = ('Ahmed', 'Ali', 'Samer') # tuple 
In [4]:
friend_tuple[1]
Out[4]:
'Ali'
In [5]:
for name in friend_tuple: # loop using iteration variable 
    print(name)
Ahmed
Ali
Samer
In [6]:
for i in range(len(friend_tuple)): # loop using index 
    print(friend_tuple[i])
Ahmed
Ali
Samer

A tuple is a list but ...

  1. Immutable
  2. Simpler and more efficient in terms of memory use and performance than lists (faster)
In [7]:
friend_tuple[2] = 'Mohammed' # error tuples are immputable 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-4fe5b60be4d8> in <module>
----> 1 friend_tuple[2] = 'Mohammed' # error tuples are immputable

TypeError: 'tuple' object does not support item assignment
In [8]:
friend_list[2] = 'Mohammed' # mutable 
print(friend_list)
['Ahmed', 'Ali', 'Mohammed']

Tuple assignment

In [9]:
(x, y) = (4, 'fred')
In [10]:
x
Out[10]:
4
In [11]:
y
Out[11]:
'fred'
In [12]:
def my_divmod(x, y):
    reminder = x % y
    result = x // y 
    return reminder, result
In [13]:
my_divmod(23, 5)
Out[13]:
(3, 4)
In [14]:
(a, b) = my_divmod(23, 5)
In [15]:
a
Out[15]:
3
In [16]:
b
Out[16]:
4
In [17]:
bag = {'books': 1, 'candy': 3, 'pen': 1}
In [18]:
bag.items()
Out[18]:
dict_items([('books', 1), ('candy', 3), ('pen', 1)])
In [19]:
for k, v in bag.items():
    print('{}\t{}'.format(k, v))
books	1
candy	3
pen	1

Tuple Comparison

In [20]:
(0, 1, 2) < (5, 1, 2)
Out[20]:
True
In [21]:
(0, 1, 3) < (5, 1, 2)
Out[21]:
True
In [22]:
(0, 1, 2000000) < (0, 3, 4)
Out[22]:
True
In [23]:
(1, 1, 2000000) < (0, 3, 4)
Out[23]:
False
In [24]:
( 'Jones', 'Sally' ) < ('Jones', 'Sam')
Out[24]:
True
In [25]:
d = {'a':10, 'c':22, 'b':1}
d.items()
Out[25]:
dict_items([('a', 10), ('c', 22), ('b', 1)])

Sort dictionary by keys

In [26]:
sorted(d.items())
Out[26]:
[('a', 10), ('b', 1), ('c', 22)]
In [27]:
sorted(d.items(), reverse=True)
Out[27]:
[('c', 22), ('b', 1), ('a', 10)]
In [28]:
# can't compare different types 
3 > 'a'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-554bcb615132> in <module>
      1 # can't compare different types
----> 2 3 > 'a'

TypeError: '>' not supported between instances of 'int' and 'str'

Sort dictionary using the values

In [29]:
tmp = list() # tmp = []  
for k, v in d.items():
    tmp.append( (v, k) )
print(tmp)
[(10, 'a'), (22, 'c'), (1, 'b')]
In [30]:
sorted(tmp)
Out[30]:
[(1, 'b'), (10, 'a'), (22, 'c')]
In [31]:
sorted(tmp, reverse=True)
Out[31]:
[(22, 'c'), (10, 'a'), (1, 'b')]

Sort Dictionary by values in one line

In [32]:
sorted( [ (v,k) for k,v in d.items() ] )
Out[32]:
[(1, 'b'), (10, 'a'), (22, 'c')]
In [33]:
sorted( [ (v, k) for k, v in d.items() ], reverse=True  )
Out[33]:
[(22, 'c'), (10, 'a'), (1, 'b')]
In [34]:
# top n elements 
sorted([(v, k) for k, v in d.items() ], reverse=True)[:2]
Out[34]:
[(22, 'c'), (10, 'a')]

Write a program take an input from the user and to:

  1. print the word counts sorted alpabetically
  2. print the top 5 most frequent words
In [35]:
text = 'the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car'
words = text.split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1 
print(counts)
{'the': 7, 'clown': 2, 'ran': 2, 'after': 1, 'car': 3, 'and': 3, 'into': 1, 'tent': 2, 'fell': 1, 'down': 1, 'on': 1}
In [36]:
# 1. print the word counts sorted alpabetically
print(sorted(counts.items()))
[('after', 1), ('and', 3), ('car', 3), ('clown', 2), ('down', 1), ('fell', 1), ('into', 1), ('on', 1), ('ran', 2), ('tent', 2), ('the', 7)]
In [37]:
# 2. print the top 5 most frequent words 
print(sorted([ (v,k) for k,v in counts.items()], reverse=True)[:5])
[(7, 'the'), (3, 'car'), (3, 'and'), (2, 'tent'), (2, 'ran')]