Tuples and Lists

Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values.

In [13]:
t = () #empty tuple
In [3]:
type(t)
Out[3]:
tuple
In [5]:
te = (1,2,"three")
te
Out[5]:
(1, 2, 'three')
In [6]:
te2 = (4, "five", 6)
In [8]:
te + te2 #tuple addition
Out[8]:
(1, 2, 'three', 4, 'five', 6)
In [11]:
te[1] #get value based on index
Out[11]:
2
In [12]:
te[1] = 4 #fails because remeber tuples are immutable
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-30df18e7182b> in <module>()
----> 1 te[1] = 4 #fails because remeber tuples are immutable

TypeError: 'tuple' object does not support item assignment
In [16]:
te[1:2] #Notice the comma after 2 which tells it is a tuple not any single element
Out[16]:
(2,)

Swaping is easy in tuple

In [17]:
x= (5)
y= (7)
(x,y) = (y,x)
In [18]:
x
Out[18]:
7
In [19]:
y
Out[19]:
5

More than one value can be returned by a function as a tuple

In [21]:
def quotient_and_reminder(x,y):
    q = x//y
    r = x% y
    return (q,r)
(quo, rem) = quotient_and_reminder(4,5)
print(quo)
print(rem)
0
4

Tuples are iteratable

In [23]:
t = (1, "two", 3 , 5, "onezerozero")
for i in t:
    print(i)
1
two
3
5
onezerozero

Lists

List is one of the simplest and most important data structures in Python. Lists are enclosed in square brackets [ ] and each item is separated by a comma. Lists are collections of items where each item in the list has an assigned index value. A list is mutable, meaning you can change its contents.

In [42]:
a_list =[] #empty list
In [44]:
L = [1,2,3,"four"]
In [45]:
L
Out[45]:
[1, 2, 3, 'four']
In [46]:
type(L)
Out[46]:
list
In [47]:
L[1]
Out[47]:
2
In [48]:
L[2]+1
Out[48]:
4
In [51]:
L[3] + "-4-2"
Out[51]:
'four-4-2'

The Big difference between Tuple and List

In [52]:
L
Out[52]:
[1, 2, 3, 'four']
In [53]:
L[2] = 7
In [55]:
L # the value changes
Out[55]:
[1, 2, 7, 'four']

List can also be iterated over

In [57]:
L = [1,2,3,4]
total=0

for i in L:
    total += i
    
print(total)
10
In [64]:
L = [1,2,3,4]
In [65]:
L.append(5) # adds 5 at the end
In [66]:
L
Out[66]:
[1, 2, 3, 4, 5]
In [82]:
L2 = [6,7,8]
L2
Out[82]:
[6, 7, 8]
In [69]:
L + L2 #concatinate
Out[69]:
[1, 2, 3, 4, 5, 6, 7, 8]
In [83]:
L2.extend([9,10]) #addes elements at the end
In [84]:
L2 
Out[84]:
[6, 7, 8, 9, 10]
In [85]:
del(L2[2]) #remove second element
In [86]:
L2
Out[86]:
[6, 7, 9, 10]
In [87]:
L2.pop() #remove last element 
L2
Out[87]:
[6, 7, 9]
In [89]:
L2.remove(7) #searchs and removes first occurence , the second 7 still remains if any
In [90]:
L2
Out[90]:
[6, 9]
In [91]:
s = "abc"
list(s)
Out[91]:
['a', 'b', 'c']
In [92]:
s = " I - am mad"
s.split("-") # splits at "-"
Out[92]:
[' I ', ' am mad']
In [94]:
L = ['a', 'b', 'c']
''.join(L) # joins all the elements from list
Out[94]:
'abc'
In [95]:
'_'.join(L)
Out[95]:
'a_b_c'
In [96]:
L = [2,7,1,9,0]
L
Out[96]:
[2, 7, 1, 9, 0]
In [97]:
sorted(L)
Out[97]:
[0, 1, 2, 7, 9]
In [100]:
L.sort()
L
Out[100]:
[0, 1, 2, 7, 9]
In [101]:
L.reverse()
L
Out[101]:
[9, 7, 2, 1, 0]
In [108]:
L.sort
Out[108]:
<function list.sort>
In [122]:
L.insert(2,1)
In [124]:
L.pop()
Out[124]:
1
In [125]:
L
Out[125]:
[1, 10, 1, 100, 9, 7, 2, 1, 0, 1]
In [126]:
L.pop(2)
Out[126]:
1
In [128]:
L.reverse()
In [129]:
L= [100, 0, 1, 4, 4, 1, 6, 3, 4]
In [134]:
L.reverse()
In [136]:
L.index(1) #index of 1
Out[136]:
2
In [135]:
L
Out[135]:
[100, 0, 1, 4, 4, 1, 6, 3, 4]

Mutation, Aliasing, Cloning

Lists are mutable hence when alias is created and changes are made to the alias same original list is changed.

In [137]:
L1 = [1,2,3,4]
L2 = L1
In [138]:
L1
Out[138]:
[1, 2, 3, 4]
In [139]:
L2
Out[139]:
[1, 2, 3, 4]
In [140]:
L2.append(5)
In [141]:
L2 # 5 is added to the end of L2 because of previous command
Out[141]:
[1, 2, 3, 4, 5]
In [143]:
L1 # 5 is added even though no operation was performed on L1, beacause both L1 and L2 points to same lists.
Out[143]:
[1, 2, 3, 4, 5]
In [144]:
#### TO avoide this its better to assign them sepereatly 
L1 = [1,2,3,4]
L2 = [1,2,3,4]
In [145]:
L1
Out[145]:
[1, 2, 3, 4]
In [146]:
L2
Out[146]:
[1, 2, 3, 4]
In [147]:
L2.append(5)
L2
Out[147]:
[1, 2, 3, 4, 5]
In [148]:
L1 # you see L1 remains the same 
Out[148]:
[1, 2, 3, 4]
In [149]:
#### Another way to do this is 

L2 = L1[:]
In [150]:
L2
Out[150]:
[1, 2, 3, 4]
In [151]:
L1
Out[151]:
[1, 2, 3, 4]
In [152]:
L2.append(5)
In [154]:
L1 # not changed
Out[154]:
[1, 2, 3, 4]

use of sort() and sorted ()

In [155]:
L1 = [ 6, 1, 8, 0]
L1.sort() # no output
In [156]:
L1 # it sorts L1 , hence L1 is altered 
Out[156]:
[0, 1, 6, 8]
In [158]:
L2 = [8,0,1,4]
sorted(L2) # gives sorted list output
Out[158]:
[0, 1, 4, 8]
In [159]:
L2 # unchanged L2 
Out[159]:
[8, 0, 1, 4]
In [160]:
L1 = [ 6, 1, 8, 0]
L2 = [8,0,1,4]
L3 = [L1]
In [161]:
L3
Out[161]:
[[6, 1, 8, 0]]
In [162]:
L3.append(L2)
In [163]:
L3
Out[163]:
[[6, 1, 8, 0], [8, 0, 1, 4]]
In [164]:
L3.append(100)
In [165]:
L3 #notice how the list is changing and the square brackets 
Out[165]:
[[6, 1, 8, 0], [8, 0, 1, 4], 100]
In [167]:
### Now suppose i make change to L1
L1.append(999)
In [168]:
L1 #L1 changes , no surpise there 
Out[168]:
[6, 1, 8, 0, 999]
In [169]:
L3 # 999 is added to L3 also , becasue L1 points to location which is inside L3
Out[169]:
[[6, 1, 8, 0, 999], [8, 0, 1, 4], 100]

Since during itiration the size of the list can change making a copy of the list is better and refer to it.


Functions as Objects - MAPS

In [177]:
for i in map(abs,[-1,2,-3,4]): #takes function 'abs' and applies to each number in the list
    print(i)
1
2
3
4
In [180]:
L1 = [65,0,187,24]
L2 = [76,99,27,1983]

for i in map(max, L1, L2): #gives max out of both the list 
    print(i)
76
99
187
1983

Dictionaries

A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.

In [2]:
dict1 = {}
In [3]:
type(dict1)
Out[3]:
dict
In [6]:
dict2 = {'1': 'a', '2':'b', '3':'c'} # key value pair
dict2
Out[6]:
{'1': 'a', '2': 'b', '3': 'c'}
In [5]:
dict2['1']
Out[5]:
'a'
In [7]:
dict2['4'] = 'd' #add elements to dict2
dict2
Out[7]:
{'1': 'a', '2': 'b', '3': 'c', '4': 'd'}
In [8]:
'1' in dict2
Out[8]:
True
In [9]:
'5' in dict2
Out[9]:
False
In [10]:
'c' in dict2 #checks ony for key not value
Out[10]:
False
In [11]:
del(dict2['2']) #delet entry from dict2
In [12]:
dict2
Out[12]:
{'1': 'a', '3': 'c', '4': 'd'}
In [13]:
dict2.keys()  
Out[13]:
dict_keys(['1', '3', '4'])
In [14]:
dict2.values()
Out[14]:
dict_values(['a', 'c', 'd'])

their order can be anything with anything in them .

In [15]:
d = {4:{1:0},(1,3):"number", "const" :[1,3.5,"list"]} # dict with lot of other things list tuple list strings
d
Out[15]:
{(1, 3): 'number', 4: {1: 0}, 'const': [1, 3.5, 'list']}
In [27]:
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}

animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
def how_many(aDict):
    '''
    aDict: A dictionary, where all the values are lists.

    returns: int, how many values are in the dictionary.
    '''
    n=0
    values = aDict.values()
    for i in values:
        n += len(i)
    return(n)
print(how_many(animals))
6
In [19]:
animals
Out[19]:
{'a': ['aardvark'],
 'b': ['baboon'],
 'c': ['coati'],
 'd': ['donkey', 'dog', 'dingo']}

Reference

  • edX course offered by MIT
  • 6.00.1x Introduction to Computer Science and Programming Using Python