Python Unit 3 Notes
Python Unit 3 Notes
Python Unit 3 Notes
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: simple sorting, histogram, Students marks
statement, Retail bill preparation.
LISTS
Like a string, a list is a sequence of values. In a string, the values are characters; In a list, they can be
of any type. The values in a list are called elements or sometimes items.
A list need not be homogenous. The elements of a list don’t have to be the same type. A list can contain
different data type items such as string, integer, float, real and another list. Each and every item has its unique
index.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ ]):
>>>L1=[10, 20, 30, 40] #List of four Integers
>>>L2=[‘Apple’, ‘Banana’, ‘Orange’] #List of three Strings
>>>L3=[‘spam’, 2.0, 5, [10, 20]] #list with string, a float, an integer, and another list
>>>L4=[] #A list that contains no elements is called an empty list;
Mutability in Lists
To access the elements of a list the bracket operator is used. The expression inside the brackets specifies
the index. The indices starts at 0.
Any integer expression can be used as an index. If an index has a negative value, it counts backward
from the end of the list.
>>> L2=[‘Apple’, ‘Banana’, ‘Orange’]
>>> L2[0]
‘Apple’
Unlike strings, lists are mutable. We can delete or replace the items or elements in the list.
>>> L2[1]= ‘Grapes’ #replaces ‘Banana’
>>> L2
[‘Apple’, ‘Grapes’, ‘Orange’]
Updating list
Single or multiple elements can be updated in a list by giving the slice on the lefthand side of the
assignment operator and also can add the elements in a list with the append() method.
Example.py
s=['Red','green','Blue','yellow','Purple']
print("value at index 2:",s[2])
Output:
s[2]='Lavender'
print(s) value at index 2: Blue
s.append('Orange') ['Red', 'green', 'Lavender', 'yellow', 'Purple']
print(s) ['Red', 'green', 'Lavender', 'yellow', 'Purple', 'Orange']
Example.py
s=['Red','green','Blue','yellow','Purple']
print(s) Output:
del s[2] ['Red', 'green', 'Blue', 'yellow', 'Purple']
print(s)
['Red', 'green', 'yellow', 'Purple']
s.remove('yellow')
print(s) ['Red', 'green', 'Purple']
LIST OPERATIONS
List Operations:
List respond to the + and * operators much like strings; they mean concatenation and repetition here
too, expect that the result is a new list, not a string.
LIST SLICES
We can access a range of items in a list by using the slicing operator(colon :)
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the
end. So if you omit both, the slice is a copy of the whole list:
>>> t[:]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
Since lists are mutable, it is often useful to make a copy before performing operations that modify lists.
Slicing can be bets 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.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 Index
K E C P U B L I s h e r s
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Negative Index
LIST METHODS
List method is a method to list all the elements in the set. Python provides methods that operates on
lists. They are accessed as list.method( ).
Output:
[‘guava’ , ‘apple’ , ‘orange’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
2
[‘guava’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
append(): reverse():
This method appends / adds the pass object (v) to This method reverses the element in the list.
the existing list.
list1=[1,2,3,4] list1=[5,2,10,4]
list1.append(99) list1.reverse()
print(list1) print(list1)
Output: Output:
[1, 2, 3, 4, 99] [4, 10, 2, 5]
insert(): count():
This method insert the given element at the This method returns count of how many times
specified position. elements occur in the list.
list1=[1,2,3,4] list1=[5,2,10,4,3,5]
list1.insert(1,100) print(list1.count(5))
print(list1) Output:
Output: 2
[1, 100, 2, 3, 4]
index():
remove(): This method returns the index value of an element.
Removes the element from the list. If there is no
element then it displays error. list1=[5,2,10,4,3]
list1=[1,2,3,4] print(list1.index(10))
list1.remove(4) Output:
print(list1) 2
Output:
[1, 2, 3] pop():
This method removes the element from the list at
extend(): the specified index. If the index value is not
This method appends the contents of the list. specified it removes the last element from the list.
list1=[5,2,10,4,3]
list1=[1,2,3,4] print(list1.pop(4))
list1.extend([10,20,30]) print(list1.pop(7))
print(list1) Output:
Output: 3
[1, 2, 3, 4, 10, 20, 30] Traceback (most recent call last):
File "python", line 3, in <module>
sort(): IndexError: pop index out of range
This method sorts the element either alphabetically
or numerically. del():
list1=[5,2,10,4] Element to be deleted is mentioned using list name
list1.sort() and index.
print(list1)
Output: list1=[5,2,10,4,3]
[2, 4, 5, 10] del list1[3]
print(list1)
Output:
[5, 2, 10, 3]
LIST LOOP
Creating list using range( )
The range( ) functions returns an immutable sequence object of integers between the given start integer
to the stop integer.
It generates a list of numbers, which is generally used to iterate over with loops.
Syntax:
range(stop)
range(start, stop[, step])
where,
start – starting number of the sequence
stop – generate numbers up to, but not including this number.
step – integer value which determines the increment between each integer in the sequence
Example
A short hand for loop that will print all items in a list:
CLONING LISTS:
Cloning is different from aliasing. Aliasing just creates another name for the same list. Cloning creates
a new list with same values under another name. Taking any slice of a list creates a new list.
Example:
fruits=[“apples”,”pear”,”grapes”,”orange”,”mango”]
fruit_list=fruits
clonefruit=fruit_list[:]
clonefruit.append(“banana”) OUTPUT:
fruit_list[1]=”Lemon”
Original List: [“apples”, “Lemon”, “grapes”, “orange”, “mango”]
print “Original List:”,fruits
print “Alias List:”,fruit_list Alias List: [“apples”, “Lemon”, “grapes”, “orange”, “mango”]
print “clone List:”,clonefruit
clone List: [“apples”, “pear”, “grapes”, “orange”,
“mango”, “banana”]
LIST PARAMETERS
When you pass a list to a function ,the function gets a reference to the list.If the function modifies the
list,the caller sees the change.
For ex: delete _head removes the first element from a list:
def delete_head(t):
del t[0]
>>> letters=[‘a’,b’,’c’]
>>>delete_head(letters)
>>>letters
[‘b’,’c’]
The parameter‘t’ and the variable letters are aliases from the same object.
TUPLE
A tuple is a sequence of values. The values can be any type. They are immutable (i.e)objects whose
value is unchangeable once they are created.
Tuple can be created by putting different values separated by comma;the parantheses are optional.
Example:
No’s_Tuple=(1,2,3)
print No’s_tuple
Nested _tuple=(“string”,[‘list’,’in’,’tuple’],(‘tuple’,’in’,tuple’)) OUTPUT:
print Nested _tuple[0] (1, 2, 3)
print (Nested_tuple[1] string
print Nested _tuple[2] ['list', 'in', 'tuple']
Mixed_tuple=3,”kg”,”apples” ('tuple', 'in', 'tuple')
print(Mixed_tuple) (3, 'kg', 'apples')
Nos,measure,what=Mixed_tuple 3
print(Nos) kg
print(measure) apples
print(what)
OPERATIONS IN TUPLE
Two operators + and * is allowed in tuples. ‘+’ concatenates the tuples and ‘*’ repeates the tuple
elements a given number of times.
Ex:
t1= (1,2,3,4,7,8,9)
t2=(‘a’,)*5 OUTPUT:
t3=t1+t2
print “Add operation:”,t3 Add operation: (1, 2, 3, 4, 7, 8, 9, 'a', 'a', 'a', 'a', 'a')
print “Repeat operation:”,t2
Repeat operation: ('a', 'a', 'a', 'a', 'a')
SLICING AND INDEXING OF TUPLES:
a=(‘physics’,’chemistry’,1997,2000)
b=(1,2,3,4,5) OUTPUT:
c=(“x”,”y”,(10,4,5))
a[0]: physics
print “a[0]: ”,a[0]
c[2]: (10, 4, 5)
print ”c[2]: ”,c[2]
b[-2]: 4
print “b[-2]: ”,b[-2]
b[1:3]: (2, 3)
print “b[1:3]: ”,b[1:3]
Tuples are immutable; the elements cannot be changed. In lists the elements can be deleted.In
tuples elements cannot be deleted. However the entire tuple can be deleted using del.Similarly the elements
cannot be modified in a tuple.
In tuple we can replace one tuple with another, but can’t modify the elements.
TUPLE ASSIGNMENT
Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
Example: a,b,c=1,2,3
The left side is a tuple of variable; the right side is a tuple of values. Each value is assigned to its
respective variable. The number of variables on the left and the right of the assignment operator must be same.
All the expression on the right side are evaluated before any of the assignment. This features make
tuple assignment quite versatile.
For Example:
>>> (a, b, c)=(1, 2, 3)
The built-in-function divmod takes two arguments and return a tuple of two values: the quotient and
remainder. You can store the result as a tuple:
>>> t=divmod(7,3)
>>>t
>>>(2,3)
def min_max(t)
return min(t),max(t)
max and min are build-in-functions that find the largest and smallest elements of a sequence.min_max
computes both and returns a tuple of two values.
DICTIONARIES
DICTIONARY
A dictionary is set of pairs of value with each pair containing a key and an item and is enclosed in curly
brackets. It is one of the compound data type like string, list and tuple.
In dictionary the index can be immutable data type.
It is a set of zero or more ordered pairs of key and value.
The value can be any type.
Each key may occur only once in the dictionary
No key may be mutable. A key may not be a list or tuple or dictionary and so on.
Example:
dict={} #empty dictionary
d1={1:'fruit ', 2:'ve getables', 3:'cereals'}
Example:
d1={1:'fruit',2:'vegetables',3:'cereals'}
d2=dict({'name':'aa','age':40})
print(d1[1])
print(d2)
Output:
fruit
{'name': 'aa', 'age': 40}
Deletion of elements
The elements in the dictionary can be deleted by using del statements.
The entire dictionary can be deleted by specifying the dictionary variable name.
Example:
del d1[1]#remove entry with key '1'
print(d1)
d1.clear()#remove all entries in dict
print(d1)
Output:
{2: 'vegetables', 3: 'cereals'}
{}
Updating elements
In dictionary the keys are always immutable.
The values are mutable that can be modified. New-key value pair can be inserted or deleted from the
dictionary.
Example:
d3={'name':'abc','dept':'ece'}
d3['name']='xxxx'
print(d3)
Output:
{'name': 'xxxx', 'dept': 'ece'}
Length:
The len function works on dictionaries; it returns the number of key-value pairs:
>>> dict1 = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> len(dict1)
3
In Operator:
The in operator works on dictionaries; it tells you whether something appears as a key in the
dictionary (appearing as a value is not good enough).
>>> dict1= {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> 'one' in eng2sp
True
>>> 'uno' in dict1
False
To see whether something appears as a value in a dictionary, we can use the method values, which
returns the values as a list, and then use the in operator:
>>> vals = eng2sp.values()
>>> 'uno' in vals
True
1) More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate
keys are encountered during assignment, the last assignment wins.
For example −
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Mani'}
print ("dict['Name']: ", dict['Name'])
Output:
dict['Name']: Mani
2) Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed.
Following is a simple example −
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
If you use a dictionary in a for statement, it traverses the keys of the dictionary.
For example,
def histogram(s):
d=dict()
for c in s: Output:
if c not in d: >>> h = histogram('parrot')
d[c]=1 >>> print_hist(h)
else: a1
d[c]+=1 p1
return d r2
t1
print_hist prints each key and the corresponding value: o1
def print_hist(h):
for c in h:
print c, h[c]
3. str(dict)
Produces a printable string representation of a dictionary
For ex.
dict = {'Name': 'Zara', 'Age': 7} OUTPUT:
print ("Equivalent String :",str (dict))
Equivalent String : {'Age': 7, 'Name': 'Zara'}
4. type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a
dictionary type.
For ex.
dict = {'Name': 'Zara', 'Age': 7};
print ("Variable Type :", type (dict))
METHODS IN DICTIONARY
1.dict.clear()
Removes all elements of dictionary dict
Ex.
dict = {'Name': 'Zara', 'Age': 7}
OUTPUT:
print ("Start Len :",len(dict))
dict.clear() Start Len : 2
print ("End Len :",len(dict))
End Len : 0
2. dict. copy()
Returns a shallow copy of dictionary dict
Ex.
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print ("The copied value:",dict2)
3.dict.values()
The method values() returns a list of all the values available in a given dictionary.
For ex.
dict = {'Name': 'Zara', 'Age': 7}
print ("Values:",dict.values())
4.dict.key()
The method keys() returns a list of all the available keys in the dictionary
Example:
dict = {'Name': 'Zara', 'Age': 7}
print("The keys are:",dict.keys())
5. dict.has_key(key)
The method has_key() returns true if a given key is available in the dictionary, otherwise it returns a false.
Ex.
dict = {'Name': 'Zara', 'Age': 7}
print "Value :”, dict.has_key('Age')
print "Value :”,dict.has_key('Sex')
6.dict.item()
The items() method returns a view object that displays a list of a given dictionary's (key, value) tuple
pair.The items() method doesn't take any parameters.
For.ex
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())
7.dict.fromkeys()
The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Syntax:
dict.fromkeys(seq [ , value] )
For ex.
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'
vowels = dict.fromkeys(keys, value)
print(vowels)
8. update()
The method update() adds dictionary dict2's key-values pairs in to dict. This function does not
return anything.
For ex.
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Gender': 'female' }
dict.update(dict2)
print ("The updated value :",dict)
Python supports a concept called “list comprehensions”.It can be used to construct lists in a very
natural,easy way,like a mathematics is used to do.
In python, we can write the expression almost exactly like a mathematics with special cryptic syntax.
For example:
>>> L=[X**2 for x in range (10)]
>>> L
[0,1,4,9,16,25,36,49,64,81]
The above code creates a list of square numbers from 0 to 9.This list can be created using a
simplified expression “X**2 for x in range (10)”.This is basically list comprehension.
The list comprehension is achieved using the tools like map, lambda, reduce and filter
MAP:
The map() function applies the values to every member of the list and returns the result.
The map function takes two arguments .
Syntax: result=map(function,sequence)
Example:
>>>def increment_by_three(x):
return x+3
>>>new_list=list(map(increment_by_three,range(10)))
>>>new_list
OUTPUT:
[3,4,5,6,7,8,9,10,11,12]
Another example: There is a build in function for calculating length of a string and and i.e len().We can pass
this function to map and find the length of every element in the list.
>>> names=[‘Sandip’,’Lucky’,’Mahesh’,’Sachin’]
>>>lengths=list(map(len,names))
>>>lengths
[6,5,6,6]
FILTER:
The filter() function selects some of the elements and filters out others .If we use it wit list
comprehension,it is almost equivalent to the filter build-in. This function takes two arguments.
Syntax: result=filter(function,sequence)
for example:
>>>def even_fun(x):
return x%2= =0
>>>r=filter(even_fun,[1,2,3,4,5])
>>>list(r)
[2,4]
In above example,using filter() function the odd numbers are filtered out and only even numbers are
displayed.
LAMBDA:
The lambda function is a simple inline function that is used to evaluate the expression using the given list
of arguments.
Where the argument_list consists of a comma separated list of arguments and the expression is an arithmetic
expression using these arguments.
Example: >>>sum=lambda x,y:x+y
>>>sum(1,3)
4
REDUCE:
The kind of function that combines sequence of elements into a single value is called reduce function.
This function takes two arguments.
Result=reduce(function,sequence)
The function reduce() had been dropped from core of python when migratin to python 3
Hence for using the reduce function we have to import functools to be capable of using reduce.\
>>>import functools
>>>functools.reduce(lambda x,y:x+y[1,2,3,4])
10
ILLUSTRATIVE PROGRAMS
1.Selection Sort
4. Merge Sort
source = [10,90,30,20]
for i in range(len(source)): def mergeSort(alist):
mini = min(source[i:]) print("Splitting ",alist)
min_index = source[i:].index(mini) if len(alist)>1:
source[i + min_index] = source[i] mid = len(alist)//2
source[i] = mini lefthalf = alist[:mid]
print(source) righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
2.Insertion Sort i=0
def insertionSort(alist): j=0
for index in range(1,len(alist)): k=0
currentvalue = alist[index] while (i < len(lefthalf)) and (j < len(righthalf)):
position = index if lefthalf[i] < righthalf[j]:
while position>0 and alist[position- alist[k]=lefthalf[i]
1]>currentvalue:
i=i+1
alist[position]=alist[position-1]
position = position-1 else:
alist[position]=currentvalue alist[k]=righthalf[j]
j=j+1
alist=[12,34,67,30,82] k=k+1
insertionSort(alist) while i < len(lefthalf):
print(alist) alist[k]=lefthalf[i]
i=i+1
3.Histogram
k=k+1
while j < len(righthalf):
def histogram(s):
d=dict() alist[k]=righthalf[j]
for c in s: j=j+1
if c not in d: k=k+1
d[c]=1 print("Merging ",alist)
else: n = input("Enter the size of the list: ")
d[c]+=1 alist = [30,50,10,70]
return d
mergeSort(alist)
def print_hist(h): print(alist)
for c in h:
print c, h[c]
PART- A (2 Marks)
1. What is a list?(Jan-2018)
A list is an ordered set of values, where each value is identified by an index. The values that make up a list are
called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of
a list can have any type.
4. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]
>>> list[:4]
[’a’, ’b’, ’c’, ’d’]
>>> list[3:]
[’d’, ’e’, ’f’]
11. Write a program in Python returns a list that contains all but the first element of the given list.
def tail(list):
return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print rest [2, 3]
12. Write a program in Python to delete first element from a list.
def deleteHead(list): del list[0]
Here’s how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]
24. Write python program for swapping two numbers using tuple assignment?
a=10 b=20
a,b=b,a
print(“After swapping a=%d,b=%d”%(a,b))
27. Give a function that can take a value and return the first key mapping to that value in a dictionary.(Jan
2019)
a={‘aa’:2, ”bb”:4}
print(a.keys()[0])
28. How to create a list in python? Illustrate the use of negative indexing of list with example. (May 2019)
List Creation:
days = ['mon', 2]
days=[] days[0]=’mon’ days[1]=2
Negative Indexing:
Example:
>>> print(days[-1])
Output: 2
29. Demonstrate with simple code to draw the histogram in python. (May 2019)
def histogram( items ): Output:
for n in items: **
output = '' times = n ***
while( times > 0 ): ******
output += '*' times = times - 1 print(output)
histogram([2, 3, 6, 5])
30. How will you update list items? Give one example. (Nov / Dec 2019)
Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the
list items
fruit = ["banana","apple","cherry"] print(fruit)
['banana', 'apple', 'cherry'] fruit[0] = "pear"
fruit[-1] = "orange" print(fruit)
['pear', 'apple', 'orange']
31. Can function return tuples? If yes Give examples. (Nov / Dec 2019)
Function can return tuples as return values. def circle_Info(r):
#Return circumference and area and tuple c = 2 * 3.14 * r Output
a = 3.14 * r * r return(c,a) (62.800000000000004, 314.0)
print(circle_Info(10))