Unit IV
Unit IV
UNIT IV
LISTS,TUPLES,DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning
lists, list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries:
operations and methods; advanced list processing - list comprehension; Illustrative
programs: selection sort, insertion sort, merge sort, histogram.
4.1 LIST:
Python offers a range of compound datatypes often referred to as sequences.
List is one of the most frequently used and very versatile datatype used in Python.
Like a string, a list is a sequence of values. In a string the values are character , but
in a list they can be any type.
It can have any number of items and they may be of different types (integer, float,
string etc.).
Example:
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
Also, a list can even have another list as an item. This is called nested list.
# nested list
Trying to access an element other that this will raise an IndexError. The
index must be an integer. We can't use float or other types, this will result
into TypeError.
Example 1:
>>>my_list = ['p','r','o','b','e']
>>>print(my_list[0])
# Output: p
>>>print(my_list[2])
# Output: o
>>>print(my_list[4])
# Output: e
i)Nested indexing
Example 1:
>>>n_list = ["Happy", [2,0,1,5]]
99
>>>print(n_list[0][1])
# Output: a
>>>print(n_list[1][3])
# Output: 5
ii)Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.
>>>my_list = ['p','r','o','b','e']
>>>print(my_list[-1])
# Output: e
>>>print(my_list[-5])
# Output: p
Example 1:
>>>my_list = ['p','r','o','g','r','a','m','i','z']
>>>print(my_list[2:5])
# elements 3rd to 5th
>>>print(my_list[:-5])
# elements beginning to 4th
>>>print(my_list[5:])
# elements 6th to end
>>>print(my_list[:])
100
Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need two index that will slice
that portion from the list.
odd = [1, 3, 5]
Example 1:
>>>print(odd + [9, 7, 5])
# Output: [1, 3, 5, 9, 7, 5]
Example 2:
>>>print(["re"] * 3)
#Output: ["re", "re", "re"]
101
Example 1:
>>>my_list = ['p','r','o','b','l','e','m']
>>>print('p' in my_list)
# Output: True
>>>print('a' in my_list)
# Output: False
>>>print('c' not in my_list)
# Output: True
Example:
>>>odd = [2, 4, 6, 8]
>>>odd[0] = 1
>>> print(odd)
# change the 1st item
# Output: [1, 4, 6, 8]
>>>odd[1:4] = [3, 5, 7]
>>> print(odd)
# change 2nd to 4th items
# Output: [1, 3, 5, 7]
We can add the element in the list by using append() and extend() method.
Both are used to add items at the end of the original list.
102
i) append()
We can add only one item to a list using append() method .
Syntax:
Listname.append(object)
Example 1:
>>>odd = [1, 3, 5]
>>>odd.append(7)
>>>print(odd)
# Output: [1, 3, 5, 7]
ii) extend()
To add several items using extend()method.
Syntax:
Listname.extend(seq)
Example 1:
>>>odd.extend([9, 11, 13])
>>>print(odd)
# Output: [1, 3, 5, 7, 9, 11, 13]
Syntax:
Listname.insert(index,object)
103
Example1:
>>>odd = [1, 9]
>>>odd.insert(1,3)
>>> print(odd)
# Output: [1, 3, 9]
>>>odd[2:2] = [5, 7]
>>>print(odd)
# Output: [1, 3, 5, 7, 9]
4.1.3.c Removing items from a list:
We can use remove() method to remove the given item or pop() method to
remove an item at the given index.
The pop() method removes and returns the last item if index is not provided.
This helps us implement lists as stacks (first in, last out data structure).
Example1:
>>>my_list = ['p','r','o','b','l','e','m']
>>>my_list.remove('p')
>>>print(my_list)
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
>>>print(my_list.pop(1))
# Output: 'o'
>>>print(my_list)
# Output: ['r', 'b', 'l', 'e', 'm']
>>>print(my_list.pop())
# Output: 'm'
>>>print(my_list)
# Output: ['r', 'b', 'l', 'e']
>>>my_list.clear()
104
>>>print(my_list)
# Output: []
Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.
Example 1:
Example1:
>>>my_list = ['p','r','o','b','l','e','m']
>>>del my_list[2]
>>>print(my_list)
# delete one item
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
>>>del my_list
>>>print(my_list)
# delete entire list
# Error: List not defined
They are accessed as list.method(). Some of the methods have already been
used above.
Example :
>>>my_list = [3, 8, 1, 6, 0, 8, 4]
106
>>>print(my_list.index(8))
# Output: 1
>>>print(my_list.count(8))
# Output: 2
>>>my_list.sort()
>>>print(my_list)
# Output: [0, 1, 3, 4, 6, 8, 8]
>>>my_list.reverse()
>>>print(my_list)
# Output: [8, 8, 6, 4, 3, 1, 0]
Function Description
all() Return True if all elements of the list are true (or if the list is empty).
Return True if any element of the list is true. If the list is empty,
any()
return False.
enumerate( Return an enumerate object. It contains the index and value of all the
) items of list as a tuple.
sorted() Return a new sorted list (does not sort the list itself).
Example 1:
>>>listone=[‘cat’,’dog’,’lion’,’elephant’,’zebra’]
>>>len(listone)
Output:
5
Example 2:
>>>numberlist=[1,5,7,9,10,12]
>>>max(numberlist)
Output:
12
>>>listone=[‘cat’,’dog’,’lion’,’elephant’,’zebra’]
>>>max(listone)
Output:
Elephant
Example 3:
>>>numberlist=[1,5,7,9,10,12]
>>>min(numberlist)
Output:
1
>>>listone=[‘cat’,’dog’,’lion’,’elephant’,’zebra’,’ox’]
>>>min(listone)
Output:
Ox
Example 4:
108
>>>numberstuple=[1,5,7,9,10,12]
>>>sum(numberstuple)
Output:
44
Example 5:
>>>numberlist=[10,5,7,9,5,12,1]
>>>sorted(numberlist)
Output:
[1,5,7,9,10,12]
Example:
>>>for fruit in ['apple','banana','mango']:
>>>print("I like",fruit)
Output:
I like ‘apple’
I like ‘banana’
I like ‘mango’
4.1.6 Aliasing
If two list refers to same object is termed as aliasing.
Example:
>>>one=[10,20,30]
>>>two=one
>>>two[1]=40
>>>print(one)
Output:[10,40,30]
Although this behavior can be useful, it is error prone. In general, it is safer
to avoid aliasing when you are working with mutable objects
109
Output:
True
False
[81,82,83]
[5,82,83]
Example:
Def deletehead(t)
Del t[0]
>>>letters=[‘x’,’y’,’z’]
>>>print(letters)
Output:
[‘y’,’z’]
Here is an example to make a list with each item being increasing power of 2.
Example:
>>>pow2 = []
>>>for x in range(10):
>>>pow2.append(2 ** x)
4.2 TUPLE
In Python programming, a tuple is similar to a list.
111
4.2.1)Creating a Tuple:
A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma. The parentheses are optional, but is a good practice to write
it.
A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).
>>>my_tuple = ()
>>>print(my_tuple)
# empty tuple
# Output: ()
>>>my_tuple = (1, 2, 3)
>>>print(my_tuple)
# tuple having integers
# Output: (1, 2, 3)
Having one element within parentheses is not enough. We will need a trailing
comma to indicate that it is in fact a tuple.
>>>my_tuple = ("hello")
>>>print(type(my_tuple))
# only parentheses is not enough
# Output: <class 'str'>
>>>my_tuple = ("hello",)
>>>print(type(my_tuple))
# need a comma at the end
# Output: <class 'tuple'>
>>>my_tuple = "hello",
>>>print(type(my_tuple))
# parentheses is optional
# Output: <class 'tuple'>
4.2.2.a Indexing
We can use the index operator [] to access an item in a tuple where the index
starts from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access
an element other that (6, 7,...) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will
result into TypeError.
Likewise, nested tuple are accessed using nested indexing, as shown in the
example below.
113
>>>my_tuple = ('p','e','r','m','i','t')
>>>print(my_tuple[0])
# Output: 'p'
>>>print(my_tuple[5])
# Output: 't'
>>>print(my_tuple[6])
# index must be in range
# If you uncomment line 14,
# you will get an error.
# IndexError: list index out of range
#my_tuple[2.0]
# index must be an integer
# If you uncomment line 21,
# you will get an error.
# TypeError: list indices must be integers, not float
The index of -1 refers to the last item, -2 to the second last item and so on.
Example:
>>>my_tuple = ('p','e','r','m','i','t')
>>>print(my_tuple[-1])
# Output: 't'
>>>print(my_tuple[-6])
# Output: 'p'
4.2.3 Slicing
We can access a range of items in a tuple by using the slicing operator -
colon ":".
114
Example:
>>>my_tuple = ('p','r','o','g','r','a','m','i','z')
>>>print(my_tuple[1:4])
# elements 2nd to 4th
# Output: ('r', 'o', 'g')
>>>print(my_tuple[:-7])
# elements beginning to 2nd
# Output: ('p', 'r')
>>>print(my_tuple[7:])
# elements 8th to end
# Output: ('i', 'z')
>>>print(my_tuple[:])
# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
This means that elements of a tuple cannot be changed once it has been
assigned. But, if the element is itself a mutable datatype like list, its nested items
can be changed.
115
Example:
#my_tuple[1] = 9
# but item of mutable element can be changed
# Output: (4, 2, 3, [9, 5])
>>>my_tuple = ('p','r','o','g','r','a','m','i','z')
>>>print(my_tuple)
Example:
>>>print(("Repeat",) * 3)
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
Example:
>>>my_tuple = ('a','p','p','l','e',)
>>>print('a' in my_tuple)
# In operation
# Output: True
>>>print('b' in my_tuple)
# Output: False
Example:
my_tuple = ('p','r','o','g','r','a','m','i','z')
del my_tuple
my_tuple
# can't delete items
# if you uncomment line 8,
# you will get an error:
# TypeError: 'tuple' object doesn't support item deletion
117
#del my_tuple[3]
# can delete entire tuple
# NameError: name 'my_tuple' is not defined
Method Description
count(x
Return the number of items that is equal to x
)
index(x
Return index of first item that is equal to x
)
Example:
>>>my_tuple = ('a','p','p','l','e',)
>>>print(my_tuple.count('p'))
# Count
# Output: 2
>>>print(my_tuple.index('l'))
# Index
# Output: 3
Function Description
Return True if all elements of the tuple are true (or if the tuple is
all()
empty).
enumerate( Return an enumerate object. It contains the index and value of all the
) items of tuple as pairs.
Take elements in the tuple and return a new sorted list (does not sort
sorted()
the tuple itself).
Example 2:
>>>numberstuple=(1,5,7,9,10,12)
>>>max(numberstuple)
Output:
12
>>>tupleone=(‘cat’,’dog’,’lion’,’elephant’,’zebra’)
>>>max(tupleone)
119
Output:
Elephant
Example 3:
>>>numberstuple=(1,5,7,9,10,12)
>>>min(numberstuple)
Output:
1
>>>tupleone=(‘cat’,’dog’,’lion’,’elephant’,’zebra’,’ox’)
>>>min(tupleone)
Output:
Ox
Example 4:
>>>tupleone=(‘cat’,’dog’,’lion’,’elephant’,’zebra’,’ox’)
>>>sorted(tupleone)
>>>print(tupleone)
Output:
[‘cat’,’dog’,’elephant’,’lion’,’ox’,’zebra’]
(‘cat’,’dog’,’lion’,’elephant’,’zebra’,’ox’)
Example 5:
>>>numberstuple=(1,5,7,9,10,12)
>>>sum(numberstuple)
Output:
44
Example 6:
>>>tuple(“programmer”)
Output:
(‘p’,’r’,’o’,’g’,’r’,’m’,’m’,’e’,’r’)
Example:
Swapping of two variables can be done easily in python. The left side is a
tuple of variables, the right side is a tuple of expressions. Each value is assigned to
its respective variable.
Example 1:
>>>a=10
>>>b=20
>>>print(“before swapping”)
>>>print(a,b)
>>>a,b=b,a
>>>print(“after swapping”)
>>>print(a,b)
Output:
Before swapping
10,20
After swapping
20,10
Example 2:
121
>>>email=’hodcse@gojaneducation.com’
>>>username,domain=email.split(‘@’)
>>>username
‘hodcse’
>>>domain
‘gojaneducation.com’
However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages:
We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee
that it remains write-protected.
4.3 Dictionaries
Python dictionary is an unordered collection of items. While other
compound data types have only value as an element, a dictionary has a
” key: value” pair.
4.3.1Dictionary Creation
Creating a dictionary is as simple as placing items inside curly braces {}
separated by comma.
An item has a key and the corresponding value expressed as a pair, key:
value.
While values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements) and must be
unique.
123
Example:
>>>my_dict = {}
# empty dictionary
As you can see above, we can also create a dictionary using the built-in
function dict().
Example:
124
>>>print(my_dict.get('age'))
# Output: 26
# >>>my_dict['address']
# Trying to access keys which doesn't exist throws error
# >>>my_dict.get('address')
If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
Example:
>>>my_dict = {'name':'Jack', 'age': 26}
>>>my_dict['age'] = 27
>>>print(my_dict)
# update value
#Output: {'age': 27, 'name': 'Jack'}
>>>my_dict['address'] = 'Downtown'
>>>print(my_dict)
# add item
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
Example:
# Output: True
>>>print(49 in squares)
# membership tests for key only not value
# Output: False
Example:
# create a dictionary
>>>print(squares)
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
>>>print(squares.popitem())
# remove an arbitrary item
# Output: (1, 1)
>>>print(squares)
# Output: {2: 4, 3: 9, 5: 25}
126
>>>del squares[5]
# delete a particular item
>>>print(squares)
# Output: {2: 4, 3: 9}
>>>squares.clear()
# remove all items
{}
Method Description
Example:
>>>marks = {}.fromkeys(['Math','English','Science'], 0)
>>>print(marks)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
Function Description
Return True if all keys of the dictionary are true (or if the dictionary is
all()
empty).
128
Here are some examples that uses built-in functions to work with dictionary.
Example:
>>>squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
>>>print(len(squares))
# Output: 5
>>>print(sorted(squares))
# Output: [1, 3, 5, 7, 9]
Example:
Example:
>>>squares = {}
>>>for x in range(6):
>>>squares[x] = x*x
Here are some examples to make dictionary with only odd items.
Examples:
>>>for s in t:
>>>res.append(s.capitalize())
>>>return res
We Can write this more concisely using a list comprehension.
Source code:
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
Output:
132
into the already sorted items. The first comparison against 93 causes 93 to be
shifted to the right. 77 and 54 are also shifted. When the item 26 is encountered,
the shifting process stops and 31 is placed in the open position. Now we have a
sorted sublist of six items.
Source code:
def insertionSort(alist):
for index in range(1,len(alist)):
134
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
Output:
Source code:
def
mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
136
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
Output:
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
137
The quick sort uses divide and conquer to gain the same advantages as the
merge sort, while not using additional storage. As a trade-off, however, it is
possible that the list may not be divided in half. When this happens, we will see
that performance is diminished.
A quick sort first selects a value, which is called the pivot value. Although
there are many different ways to choose the pivot value, we will simply use the
first item in the list. The role of the pivot value is to assist with splitting the list.
The actual position where the pivot value belongs in the final sorted list,
commonly called the split point, will be used to divide the list for subsequent calls
to the quick sort.
That 54 will serve as our first pivot value. Since we have looked at this
example a few times already, we know that 54 will eventually end up in the
position currently holding 31. The partition process will happen next. It will find
the split point and at the same time move other items to the appropriate side of the
list, either less than or greater than the pivot value.
the contents of the split point and the pivot value is now in place (Figure 14). In
addition, all the items to the left of the split point are less than the pivot value, and
all the items to the right of the split point are greater than the pivot value. The list
can now be divided at the split point and the quick sort can be invoked recursively
on the two halves.
Source code:
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first]
leftmark = first+1
rightmark = last
141
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark = leftmark + 1
Output: