Unit 4 Notes
Unit 4 Notes
LIST:
List is a collection of sequence of elements within square brackets[], separated by comma(,).
Creating a list:
A list is created by putting the values inside the square brackets separated by commas.
List indices start at 0
Eg:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Listname[index_value]
For example
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[5]: ", list2[5])
Output:
list1[0]: physics
list2[5]: 6
Types of indexing:
1.Forward indexing: indexing value starts from left and goes through right.
Eg:
S a m m y S h a r k !
0 1 2 3 4 5 6 7 8 9 10 11
2.Reverse indexing: indexing value starts from right and goes through left.
S a m m y S h a r k !
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
List Length:
This function returns the length of a list which is equal to number of elements.
Updating Lists
List can be updated by using indexing.
Eg:
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Output:
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements
To remove a list element, you can use either the del statement
Eg:
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Operations
Methods
S.
Method
No Description Syntax Example Output
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence
is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each
item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire
sequence is exhausted.
Example
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Aliasing:
If we assign one variable to another, bother variables refer to same object.
>>a=[1,2,3]
>>a=b
>>a is b
True
Here the same list have two different names, a and b. if any changes made in one list ‘a’ will
affect the other list ‘b’.
Cloning:
If we want to modify the list, want to keep a copy of the original list.
Slice operator is used for cloning a list.
Eg:
>>a=[1,2,3]
>>b=a[:]
>>print(b)
Output:
[1,2,3]
If any changes made in one list, will not affect the other.
Tuples:
Tuple is a sequence of elements written within paranthesis () and separated by comma(,).
It is immutable,
Creating a tuple
A tuple is created by putting the values inside the paranthesis separated by commas.
Eg:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements.
You are able to take portions of existing tuples to create new tuples
Eg:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print (tup3)
Output:
(12, 34.56, 'abc', 'xyz')
Output:
('physics', 'chemistry', 1997, 2000)
Operations:
1 Comparison cmp(tuple1, Compares elements of both tuple1 = ('python', 'geek') Not the same
tuple2) tuple2 = ('coder', 1)
tuples. if (cmp(tuple1, tuple2) !=
0):
# cmp() returns 0 if
matched, 1 when not
tuple1
# is longer and -1 when
tuple1 is shoter
print('Not the same')
else:
print('Same')
2 Length len(tuple) Gives the total length of the tuple2 = ('python', 'geek') 2
print(len(tuple2))
tuple.
4 Minimum min(tuple) Returns item from the tuple tuple1 = ('python', 'geek') Minimum element in
value tuple2 = ('coder', 1) tuples 1,2: geek,1
with min value. print ('Minimum element
in tuples 1,2: ' +
str(min(tuple1)) + ',' +
str(min(tuple2)))
Keys Values
Structure of Dictionary
Creating a dictionary:
1. It can be created by specifying the key and value separated by a colon(:) and the pair is
Fruits={1:apple,2:orange,3:grapes}
Fruits:{}
Characteristics of a dictionary:
Operations in dictionary:
i) Creating a dictionary:
There are two ways in creating a dictionary. They are,
months={}
2. It can be created by specifying the key and value separated by a colon(:) and the pair is
Eg:
Accessing a dictionary:
1. Adding an aelement
2. Updating the element
3. Deleting the element
4. Checking for presence of key
1. Adding an element:
To add a new element to a dictionary, assign a value to a new key.
Syntax:
Dictionary_name[new_key-value]=value
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June", 7 :
"July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}
Output:
2. Updating an element
The values in dictionary can be modified.
New key_value pairs can be inserted or deleted from the dictionary.
Syntax:
Dictionary_name[new_Key_value]=value
Eg:
months = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June", 7 :
"July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}
print(“Before updating”,months)
months[1] = "Jan" # Updating an element
print (“After Updating”,months)
Output:
Before updating: { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May",6
: "June", 7 : “July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}
3. Deleting an element:
Deletion can be done using following methods.
1.del
2.pop()
3.popitem()
1.del:
It is used to delete the elements in the dictionary.
Syntax:
Del dict_name[key]
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}
2.popitem():
It is used to delete the elements in the dictionary using the key and value.
Syntax:
Dict_name.popitem(key:value)
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}
3.pop():
It is used to delete the elements in the dictionary using the key.
Syntax:
Dict_name.popitem(key)
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}
Output:
{ 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",7 : "July",
8 : "August",9 : "September", 10 : "October"}
4.clear()
It deletes all the elements in the dictionary.
Syntax:
Dict_name.clear()
Eg:
months = { 1 : "January", 2 : "February", 3: "March", 4 : "April", 5 : "May", 6 : "June",
7 : "July", 8 : "August",9 : "September", 10 : "October", 11 : "November"}
Output:
{}
5.Sorting:
Sorts the elements in the dictionary in alphabetic order.
Eg:
months = { 1 : "January", 10 : "October", 2 : "February", 3: "March", 4 : "April", 5 :”May",
6 : "June", 9 : "September", 11 : "November” ,7 : "July", 8 : "August"}
sortedkeys = months.keys()
print (sortedkeys)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Output:
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December
Eg:
matrix1=[[1,2,3],[4,5,6],[7,8,9]]
print(“matrix[0]=”,matrix1[0])
print(“matrix[1]=”,matrix1[1])
print(“matrix[2]=”,matrix1[2])
Output:
matrix[0]=[1,2,3]
matrix[1]=[4,5,6]
matrix[2]=[7,8,9]
Histogram:
Eg:
a = (0, 1, 1, 1, 2, 3, 7, 7, 23)
def count_elements(seq) -> dict:
"""Tally elements from `seq`."""
hist = {}
for i in seq:
hist[i] = hist.get(i, 0) + 1
return hist
counted = count_elements(a)
Output:
counted
{0: 1, 1: 3, 2: 1, 3: 1, 7: 2, 23: 1}
for n in items:
output = ''
times = n
output += '='
times = times – 1
print(output)h
histogram([2, 3, 6, 5])
Output:
==
===
======
=====
List comprehensions
It provide a concise way to create lists.
It consists of brackets containing an expression followed by a for clause, thenzero or more
for or if clauses.
The expressions can be anything, meaning you can put in all kinds of objects in lists.
The result will be a new list resulting from evaluating the expression in the
context of the for and if clauses which follow it.
The list comprehension always returns a result list.
Syntax:
The list comprehension starts with a '[' and ']', to help you remember that the
result is going to be a list.
[ expression for item in list if conditional ]
Eg:
x = [i for i in range(10)]
print x
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Illustrative programs:
Output:
Before sort:
[54,26,93,17,77,31,44,55,20]
After Sort:
[17,20,26,31,44,54,55,77,93]
Step1: Compare the current element in the iteration (say A) with the previous adjacent
element to it. If it is in order then continue the iteration else, go to step 2.
Step2: Swap the two elements (the current element in the iteration (A) and the previous
adjacent element to it).
Step3: Compare A with its new previous adjacent element. If they are not in order then
proceed to step 4.
Step4: Swap if they are not in order and repeat steps 3 and 4.
Step5: Continue the iteration.
Program:
(iii)Merge sort:
Merge sort is very different than the other sorting techniques we have seen so
far.
Merge Sort can be used to sort an unsorted list or to merge two sorted lists.
Program:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
#recursion
mergeSort(lefthalf)
mergeSort(righthalf)
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
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
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])
('Splitting ', [54, 26])
('Splitting ', [54])
('Merging ', [54])
('Splitting ', [26])
('Merging ', [26])
('Merging ', [26, 54])
('Splitting ', [93, 17])
('Splitting ', [93])
('Merging ', [93])
('Splitting ', [17])
('Merging ', [17])
('Merging ', [17, 93])
('Merging ', [17, 26, 54, 93])
('Splitting ', [77, 31, 44, 55, 20])
('Splitting ', [77, 31])
('Splitting ', [77])
('Merging ', [77])
('Splitting ', [31])
('Merging ', [31])
('Merging ', [31, 77])
('Splitting ', [44, 55, 20])
('Splitting ', [44])
('Merging ', [44])
('Splitting ', [55, 20])
('Splitting ', [55])
('Merging ', [55])
('Splitting ', [20])
('Merging ', [20])
('Merging ', [20, 55])
('Merging ', [20, 44, 55])
('Merging ', [20, 31, 44, 55, 77])
('Merging ', [17, 20, 26, 31, 44, 54, 55, 77, 93])
[17, 20, 26, 31, 44, 54, 55, 77, 93]