Python Unit 3 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

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: 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’]

The in operator also works on lists:


>>> L2=[‘Apple’, ‘Banana’, ‘Orange’]
>>>’Apple’ in L2
True
>>>’Banana’ in L2
False
Traversing a List:
The most common way to traverse the elements of a list is with for loop. For loop in python is an
iterator that works on any sequence like list, tuple and string.

Example 1: Program to list contents


Output:
mylist = ['one', 'two', 'three']
number one
for x in mylist: number two
number three
print('number' ,x)

Accessing Values in Lists:


To access values in lists, use the square brackets for slicing along with the index or indices to obtain
value available at that index.

Example: Program to access the values in lists.


list1 = ['computer', 'maths', 'physics', 'chemistry']
list2 = [1,2,3,4,5] Output:
list3 = ['x', 'y', 'x'] computer
print(list1[0]) [3,4,5]
print(list2[2:5]) [‘x’, ‘y’, ‘x’]
print(list3)

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']

Deleting elements in a List


 When index of element is known then, ‘del’ keyword is used to delete.
 When element to delete is known,then remove() method is used.

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.

Python Expression Result Description


len ([1,2,3,4]) 4 Length
[1,2,3,4] + [5,6,7,8] [1,2,3,4,5,6] Concatenation
[‘Hi!’] * 2 [‘Hi!’, ‘Hi’] Repetition
2 in [1,2,3] True Membership
for x in [1,2,3,4,5]:
12345 Iteration
print(x)

The + is a concatenation operator, that concatenates lists:


>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
[1, 2, 3, 4, 5, 6]
The * is a Repetition operator, that repeats the list for a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first ex, repeats [0] four times. The second ex, repeats the list [1, 2, 3] three times.
len() is used to find the number of elements in a sequence.
>>>list1=[1,2,3,4]
>>>print(len(list1))
4
max () & min(): max(s) returns the largest value in a sequence s and min(s) returns the smallest
value in a sequence s
>>>list1=[1,2,3,4]
>>>print(max(list1))
4
>>>print(min(list1))
1
List index:
The index operator[ ] is used to access an item in a list. Index starts from 0. So, a list having 5 elements
will have index from 0 to 4.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. Nested list are accessed
using nested indexing.
Example: Program to access list elements using index.
my_list = [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] Output:
print(my_list[4]) o
n_list = [“happy”, [2,0,1,5]] [‘happy’, [2,0,1,5]]
print(n_list) a
print(n_list[0][1]) 5
print(n_list[1][3])
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.
Example : Program to use negative index in lists.
my_list = [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] Output:
print(my_list[-1]) n
print(my_list[-3]) h
print(my_list[-5]) y

LIST SLICES
We can access a range of items in a list by using the slicing operator(colon :)

The slice operator also works on lists:


>>> t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> t =[1:3]
[‘b’, ‘c’]
>>> t[ :4]
[‘a’, ‘b’, ‘c’, ‘d’]
>>> t[3:]
[‘d’, ‘e’, ‘f’]

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.

Example: Program to use slice operator in the list


my_list = [‘K’, ‘E’, ‘C’, ‘ ’, ‘P’, ‘u’, ‘b’, ‘l’, ‘i’, ‘s’, ‘h’, ‘e’, ‘r’, ‘s’]
print(my_list[0:3]) Output:
print(my_list[:-5]) [‘K’, ‘E’, ‘C’]
print(my_list[4:]) [‘K’, ‘E’, ‘C’, ‘ ’, ‘P’, ‘U’, ‘B’, ‘L’, ‘I’]
[‘P’, ‘U’, ‘B’, ‘L’, ‘I’, ‘S’, ‘H’, ‘E’, ‘R’, ‘S’]
print(my_list[:]) [‘K’, ‘E’, ‘C’, ‘ ’, ‘P’, ‘U’, ‘B’, ‘L’, ‘I’, ‘S’, ‘H’, ‘E’, ‘R’, ‘S’]

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( ).

 List methods are,


1. list.append(elem) – adds a single elements to the end of the list.
2. list.insert(index,elem) – inserts the element at the given index.
3. list.extend(list2) – adds the elements in list2 to the end of the list.
4. List.index(elem) – search for the given element from the start of the list and returns its index.
5. list.remove(elem) – search for the first instance of the given element and removes it.
6. list.sort( ) – sorts the list in place
7. list.reverse( ) – reverses the list in place
8. list.pop(index) – removes and returns the elements at the given index.
9. list.clear( ) – removes all elements from the list
10. list.count( ) – returns the count of number of items passed as an argument.
11. list.copy( ) – returns a shallow copy of the list

Example for list methods:


list = [‘apple’ , ‘orange’ , ‘grapes’]
list.append(‘banana’) #append element at end
list.insert(0, ‘gova’) #insert element at index 0
list.extend([‘chikoo’ , ‘jackfruit’]) #add elements at end
print list #[‘gova’ , ‘apple’ , ‘orange’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]
print list.index(‘orange’) #2
list.remove(‘orange’) #search and remove the element
list.pop(1) #removes and returns ‘apple’
print list #[‘gova’ , ‘grapes’ , ‘banana’ , ‘chikoo’ , ‘jackfruit’]

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

Iterate or Loop a List using ‘for’:


Example 1: To print numbers using range( ) function
for i in range(5):
Output:
print(i, end= “ ”)
01234
Example 2:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Iterate or Loop a List using ‘while’:


We can loop through the list items by using a while loop.
The len() function is used to determine the length of the list, then start at 0 and loop through the list
items by referring to their indexes.
After each iteration, the index must be incremented by one.

Example: Loop a list using while loop


mylist = range(5) Output:
i=0
while(i<len(mylist)): 01234
print(i,end= “ ”)
i+=1

Looping Using List Comprehension


List Comprehension offers the shortest syntax for looping through lists:

Example
A short hand for loop that will print all items in a list:

thislist = ["apple", "banana", "cherry"]


[print(x) for x in thislist]
ALIASING
An object with more than one references has more than one name, such object is called alias.
Example: a = [1, 2, 3]
b=a
b is a

rogram of List Aliasing OUTPUT


a=[1,2,3,4]
b=a b: [1,2,3,4]
print ’b:’,b
b.append(5) a after change in b:[1,2,3,4,5]
print ‘a after change in b:’,a

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.

Example: t = ('a', 'b', 'c',’d’, 'e')

CREATING AND ACCESSING TUPLE:

Tuple can be created by putting different values separated by comma;the parantheses are optional.

Example:

a=() #Empty tuple

b=(1,2,3) #Integer tuple

c=(1,”hello”,3.4) # Mixed tuple

Simple example for tuples:

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:

Slicing of tuples is similar to list.


Ex:

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]

DELETING AND UPDATING TUPLES:

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.

Ex : >>>t = ('a', 'b', 'c', 'd', 'e')


>>>t =(‘A’,)+t[1:]
<<<t
(‘A’, ’b’ , ’c’, ’d’, ’e’)

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)

# Program to swap a and b (without using third variable)


a=2; b=3
print(a, b) OUTPUT:
a,b=b,a
print(a, b) (2, 3)
(3, 2)
 One way to think of tuple assignment is as tuple packing/unpacking:
In tuple packing, the value on the left are ‘packed’ together in a tuple:
>>> b= (“George”,25,”20000”) #tuple packing
>>> (name, age, salary) = b #tuple unpacking
>>> name
‘George’
>>> age
25

TUPLE AS RETURN VALUE


Functions can only return value, but if the value is a tuple, the effect is the same as returning multiple
values. For example: If we want to divide two integers and compute the quotient and remainder, it is inefficient
to compute x/y and then x%y. It is better to compute them both at the same time.

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:

>>> def divmod(x,y):


Return(x/y,x%y)

>>> t=divmod(7,3)
>>>t
>>>(2,3)

Or use tuple assignment to store the elements separately:


>>>quot,rem=divmod(7,3)
>>>quot
2
>>>rem
1

Here is an example of a function that returns a tuple:

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'}

Creation and Accessing dictionary


There are two ways to create dictionaries.
1) It is created by specifying the key and value separated by a colon(:) and the
elements separated by commas and entire set of elements must be enclosed by curly braces.
2) dict() constructor that uses a sequence to create dictionary.

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

Delete Dictionary Elements


 We can either remove individual dictionary elements or clear the entire contents of a dictionary.
 To explicitly remove an entire dictionary, just use the del statement.
Following is a simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ( "dict ['Age']: " , dict ['Age'] )
print ("dict ['School']: " , dict ['School'])
Properties of Dictionary Keys:
Here are two important points to remember about dictionary keys −

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'])

When the above code is executed, it produces the following result


Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7}
TypeError: list objects are unhashable

Looping and dictionaries:

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]

Again, the keys are in no particular order.


OPERATIONS IN DICTIONARY
1. cmp(dict1, dict2)
 Compares elements of both dict.
 This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2 and 1 if dict1 > dic2.
For ex.
dict1 = {'Name': 'Zara', 'Age': 7}; OUTPUT:
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27}; Return Value : -1
Return Value : 1
dict4 = {'Name': 'Zara', 'Age': 7};
Return Value : 0
print ("Return Value :",cmp(dict1, dict2))
print ("Return Value :",cmp(dict2, dict3))
print ("Return Value :",cmp(dict1, dict4))
2. len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
For ex. OUTPUT:
dict = {'Name': 'Zara', 'Age': 7};
print ("Length : ", len (dict)) Length : 2

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)

ADVANCED LIST PROCESSING


LIST COMPREHENSION

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.

Syntax: lamda argument_list:expression

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.

2. Relate String and List? (Jan 2018)(Jan 2019) String:


String is a sequence of characters and it is represented within double quotes or single quotes. Strings are
immutable.
Example: s=”hello”
List:
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 and it is mutable.
Example:
b= [’a’, ’b’, ’c’, ’d’, 1, 3]

3. Solve a)[0] * 4 and b) [1, 2, 3] * 3.


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

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’]

5. Mention any 5 list methods.


 append()  pop()  remove()
 extend ()  index()
 sort()  insert

6. State the difference between lists and dictionary.


Lists Dictionary
 List is a mutable type meaning that it can  Dictionary is immutable and is a key
be modified. value store.
 List can store a sequence of objects in a  Dictionary is not ordered and it requires
certain order. that the keys are hashable.
 Example: list1=[1,’a’,’apple’]  Example: dict1={‘a’:1, ‘b’:2}
7. What is List mutability in Python? Give an example.
Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, i.e., their
content can be changed without changing their identity. Other objects like integers, floats, strings and tuples are
objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]

8. What is aliasing in list? Give an example.


An object with more than one reference has more than one name, then the object is said to be aliased.
Example:If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True

9. Define cloning in list.


In order to modify a list and also keep a copy of the original, it is required to make a copy of the list itself, not
just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word “copy”.
Example:
def Cloning(li1): li_copy = li1[:] return li_copy
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1) print("Original List:", li1) print("After Cloning:", li2) Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]

10. Explain List parameters with an example.


Passing a list as an argument actually passes a reference to the list, not a copy of the list. For example, the
function head takes a list as an argument and returns the first element:
Example: def head(list):
return list[0]
Here’s how it is used:
>>> numbers = [1, 2, 3]
>>> head(numbers)
>>> 1

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]

13. What is the benefit of using tuple assignment in Python?


It is often useful to swap the values of two variables. With conventional assignments a temporary variable would
be used.
For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a

14. Define key-value pairs.


The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a value
separated by a colon. In a dictionary, the indices are called keys, so the elements are called key-value pairs.

15. Define dictionary with an example.


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.
Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’

16. How to return tuples as values?


A function can only return one value, but if the value is a tuple, the effect is the same as returning multiple
values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient
to compute x/y and then x%y. It is better to compute them both at the same time.
>>> t = divmod(7, 3)
>>> print t (2, 1)

17. List two dictionary operations.


 Del -removes key-value pairs from a dictionary
 Len - returns the number of key-value pairs

18. Define dictionary methods with an example.


A method is similar to a function. It takes arguments and returns a value but the syntax is different. For example,
the keys method takes a dictionary and returns a list of the keys that appear, but instead of the function syntax
keys(dictionary_name), method syntax dictionary_name.keys() is used.
Example:>>> eng2sp.keys() [’one’, ’three’, ’two’]
19. Define List Comprehension.
List comprehensions apply an arbitrary expression to items in an iterable rather than applying function. It
provides a compact way of mapping a list into another list by applying a function to each of the elements of the
list.

20. Write a Python program to swap two variables.


x=5
y = 10
x,y=y,x
print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y))

21. Write the syntax for list comprehension.


The list comprehension starts with a '[' and ']', to help you remember that the result is going to be a list. The
basic syntax is[ expression for item in list if conditional ].
Example:
new_list = [] for i in old_list:
if filter(i): new_list.append(expressions(i))

22. How list differs from tuple. (Jan-2018)


List Tuple
 List is a mutable type meaning that it can be  Tuple is an immutable
modified. type meaning that it cannot be
 Syntax: list=[] modified.
 Example: list1=[1,’a’]  Syntax: tuple=()
 Example: tuple1=(1,’a’)

23. How to slice a list in Python. (Jan-2018)


The values stored in a list can be accessed using slicing operator, the colon (:) with indexes starting at 0 in the
beginning of the list and end with -1.
Example:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]

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))

25. What is list loop?


In Python lists are considered a type of iterable . An iterable is a data type that can return its elements separately,
i.e., one at a time.
Syntax: for <item> in <iterable>:
<body>
Example:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
print("Hi "+ name +"!")

26. What is mapping?


A list as a relationship between indices and elements. This relationship is called a mapping; each index
“maps to” one of the elements.The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses True
>>> 'Brie' in cheeses False

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))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy