0% found this document useful (0 votes)
8 views30 pages

Python Unit4

The document provides comprehensive notes on lists, tuples, and dictionaries in Python, detailing their characteristics, operations, and methods. It explains list creation, indexing, slicing, and built-in functions, along with examples of list manipulation and traversal. Additionally, it covers concepts like mutability, aliasing, cloning, and list comprehensions, emphasizing the mutable nature of lists and their use in programming.

Uploaded by

j.priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
8 views30 pages

Python Unit4

The document provides comprehensive notes on lists, tuples, and dictionaries in Python, detailing their characteristics, operations, and methods. It explains list creation, indexing, slicing, and built-in functions, along with examples of list manipulation and traversal. Additionally, it covers concepts like mutability, aliasing, cloning, and list comprehensions, emphasizing the mutable nature of lists and their use in programming.

Uploaded by

j.priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 30

EASWARI ENGINEERING COLLEGE

(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

191GES102T – PROBLEM SOLVING THROUGH PYTHON


PROGRAMMING

Unit IV -Notes

I YEAR –B.E/B.TECH
(Common to all Branches)

PREPARED BY APPROVED BY

J.Priya HOD
UNIT-IV
LIST, TUPLE AND DICTIONARIES

Lists: list operations, list slices, list methods, traversing, mutability, aliasing, list arguments, list
comprehension; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
functions, Looping and dictionaries, histogram.

LISTS:

A list is an ordered sequence of elements, the elements are separated by commas and are enclosed
in square brackets [ ]. A List is mutable sequence datatype

Syntax:
Listname=[value 2,value 2, value 3,….,value n]

Example:
A=[1,2,3,4,5], Here A is the list with a set of integers

Characteristics of lists:
• Lists are mutable, that is the elements of the list can be updated, modified and deleted
• Lists can contain same type of elements or different type of elements

Creating a list:
A list can be created using comma-separated values between square brackets.
For example:
list1 = ['physics', 'chemistry', 1997, 2000]#A list of mixed types
list2 = [1, 2, 3, 4, 5 ] # A list of integers
list3 = ["a", "b", "c", "d"] # A list of strings
a=[] #An Empty list
Creating Nested lists:
A list can be nested within another list as shown below:
Example: [1,2,[10,5]]
Example for Nested list for Matrix multiplication:
# 3x3 matrix
X = [[12,7,3], [4 ,5,6], [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0], [0,0,0,0],[0,0,0,0]]
# iterate through
rows of X for i in
range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):

2
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

OUTPUT:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

List Indexing/Accessing the elements of the list:

The elements of the list can be accessed using the indexing operator ([ ]) to select a element
from a list. The expression inside brackets is called the index, and must be an integer value. The
index indicates which element to select from the list.
Example:

Elements of a list are accessed by using an index value within square brackets, all lists have
index values 0 ... n-1, where n is the number of elements in the list. The indices that start with 0
are used to access the list from the left of the list and are known as positive indices. The indices
that start with -1 are used to access the list from the right and are known as negative indices.

#Example program to show lists, accessing elements of lists


a=[1,2,3,"hello",5]
print(a)
print(a[0])
print(a[-1])
b=[[1,2,3],[4,5,6],[7,8,9]]
print(b)
print(b[0])
print(b[1])
print(b[2])
print(b[-1])
print(b[0][1])
Output:
[1, 2, 3, 'hello', 5]
1
5
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

3
[1, 2,3]
[4, 5,6]
[7, 8,9]
[7, 8,9]
2
LIST OPERATIONS:
The following are the operations that can be performed on the lists:
1. CONCATENATION:
The concatenation operator(+) is used to concatenate two lists.
Example:
>>> list1=[10,20,30,40]
>>> list2=['python','program']
>>> list3=list1+list2
>>> list3
[10, 20, 30, 40, 'python', 'program']
2. REPETITION:
The repetition operator(*) is used to repeat the list for a given number of times.
Example:

>>> list4=[1,2,3,'python']
>>> list4*3
[1, 2, 3, 'python', 1, 2, 3, 'python', 1, 2, 3, 'python']
3. MEMBERSHIPOPERATION:
The operators in and not in operators are the membership operators in python. The in operator
is used to test whether a element is present in a list. It returns True if the element is present in the
list otherwise False. The not in operator is used to test if the element is not present in the list. It
returns True if the element is not present in the list, False otherwise
>>> list1=[1,2,3,"hello"]
>>> 1 in list1
True
>>> "Hello" in list1
False
LIST SLICES:
Slicing refers to extracting a subset of list. The operator [:] is used to perform the slice operation.
Syntax:
Listname[start:stop:step]
where start is the starting index for the slice which is included in the slice operation
stop is the stopping index for the slice which is excluded in the slice operation
step is the next index for slice which is optional
Example:
#Example for slicing lists
a=[1,2,3,4,5,6]
print(a)
print(a[0])
print(a[0:])
print(a[1:4])
print(a[1:4:2])
print(a[-1:])

4
print(a[-4:-1])
print(a[-1:-4])
Output:
[1, 2, 3, 4, 5,6]
1
[1, 2, 3, 4, 5,6]
[2, 3, 4]
[2, 4]
[6]
[3, 4,
5] []

5
LIST INBUILT METHODS:

6
clear() - Removes all items from the list
Syntax:
Listname.clear()

copy() - Returns a shallow copy of the list


Syntax:
Listname.copy()

#Example for List Methods #Append()


list1=[1,2,3,5]
print("List before appending",list1)
list1.append(10)
print("List after appending",list1)
Output:
List before appending [1, 2, 3, 5]
List after appending [1, 2, 3, 5, 10]

LIST INBUILT FUNCTIONS:


len():This function returns the number of elements in the list
syntax:
len(listname)
Example:
>>> list1=[1,2,3,4,5]
>>> len(list1)
5
max():Returns the maximum element from the list
Syntax:
max(listname)
Example:
>>> list1=[1,2,3,4,5]
>>> max(list1)
5
min():Returns the minimum element from the list
Syntax:
min(listname)
Example:
>>> list1=[1,2,3,4,5]
>>>min(list1)
1
cmp():This function is used to compare two lists. It Returns -1 if list1 is less than list2 Returns
0 if list1 is equal to list2.Returns 1 if list1 is greater than list2
syntax:
cmp(list1,list2)
list(seq):This function is used to convert the sequence such as a tuple to a list
syntax:
list(seq)

7
Example:
>>> t=(1,2,3)
>>> list(t)
[1, 2, 3]
del:
The del keyword is used to delete a particular element form the list or deletes the list itself
Syntax: del
listname[index]
del listname
Example:
>>> list1=[1,2,3,4,5]
>>> del list1[0]
>>> list1 [2, 3, 4, 5]
>>> del list1
>>> list1
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
<module> list1
NameError: name 'list1' is not defined

LIST LOOPS(LIST TRAVERSAL)


A list traversal is a means of accessing, one-by-one, the elements of a list. For example, to
add up all the elements in a list of integers, each element can be accessed one-by-one, starting
with the first, and ending with the last element. This traversal is achieved with the help of
looping statements such as for and while.
List traversal using for loop: #Example list
traversal using for loop
list1=[1,2,3,4,5]
s=0
for i in list1:
s=s+i
print("The sum of numbers in a list is",s)
Output:
The sum of numbers in a list is 15
#Example list traversal using for loop with range
list1=[1,2,3,4,5]
s=0
for i in range(0,len(list1)):
s=s+list1[i]
print("The sum of numbers in a list is",s)
Output:
The sum of numbers in a list is 15

List traversal using while loop:


#Example for list traversal using while loop
list1=[10,20,30,40,50]
i=0
while(i<len(list 1)):
print(list1[ i])
i=i+1
8
Output:
10
20
30
40
50

LIST MUTABILITY:
Lists are mutable. Mutable means that the contents of the list may be altered. The elements of the list
can be updated, deleted, or modified.
#List mutability
list1=[1,2,3,4,5]
print(list1)
list1[0]=10
print(list1)
list1.append(20)
print(list1)
del list1[2]
print(list1)
s="Python"
print(s)
s[0]='c'
print(s)
del s[0]
print(s)

OUTPUT:
[1, 2, 3, 4, 5]
[10, 2, 3, 4, 5]
[10, 2, 3, 4, 5, 20]
[10, 2, 4, 5, 20]
Python
Typeerror: 'str' object does not support item assignment

LIST ALIASING:
When two variables refer to the same object or list ,it is known as aliasing. When two variables
refer to the same list, changes made in one variable are reflected in the list

If the aliased object is mutable, changes made with one alias affect the other
Example:
#List Aliasing
list1=[1,2,3,4,5]
list2=list1
print(list1)
print("Aliased list",list2)
9
list1[0]=10 #changes in list1
print(list1)
print(list2) #changes affected the alias object
Output:
[1, 2, 3, 4, 5]
Aliased list [1, 2, 3, 4, 5]
[10, 2, 3, 4,5]
[10, 2, 3, 4,5]

List cloning:
Cloning creates a new list with same values under another name. Cloning is the process of
making a copy of the list without modifying the original list. The changes will not affect the
original copy but reflected only in the duplicate copy
Various methods of cloning:
1. Cloning by assignment:
This is done by assigning one list to another list. This creates a new reference to the original list
#Cloning by assignment
a=[1,2,3]
b=a
print(b)
Output:
[1, 2, 3]
2. Cloning byslicing
A clone of the list is created by slicing using [:]
#Cloning by Slicing
a=[1,2,3]
b=a[:]
print(a)
b[0]=10
print(b)
print(a)
Output:
[1, 2, 3]
[10, 2, 3]
[1, 2, 3]
3. Clone bylist()
A clone of the list is created by using the list() constructor.
a=[1,2,3]
b=list(a)
print(a)
print(b)
b[0]=10
print(a)
print(b)
Output:
[1, 2,3]
[1, 2,3]
[10, 2, 3]

10
LIST PARAMETERS:
A list can be passed as a parameter to the function. This parameter is passed by reference. The
changes made in the list inside the function will affect the list after returning from the function.
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.
Example:
#List parameters def
change(list1):
print("List inside function",list1)
list1[2]=90
print("List after changing",list1)
return
list1=[10,20,30]
print("List before calling function",list1)
change(list1)
print("List after calling funciton",list1)
Output:
List before calling function [10, 20, 30]
List inside function [10, 20, 30]
List after changing [10, 20, 90]
List after calling function [10, 20, 90]

Lists as Arrays
In Python, an array of numeric values is supported through the array module. We can treat lists as
arrays. While a list can store elements of multiple data types, an array contains elements only of the same
type. Therefore, we can say that, array is a container which can store a fixed number of elements that are of
the same type.
Some important terms that are frequently used while working with arrays:
Element—Each item stored in an array.
Index—Location of each element in the array is denoted by a numerical index. Every element is identified
with its index in to the array. The index of the first element is 0, second element is 1, third element is 2, so
on and so forth.

Creating an Array

11
Type code in Array

LIST COMPREHENSIONS:

List comprehensions in Python provide a concise means of generating a more varied set of
sequences than those that can be generated by the range function. Provide a concise way to apply
an operation to the values in a sequence. List comprehension creates a new list in which each
element is the result of applying a given operation to a value from a sequence. List
comprehension create a list with a sub set of elements from another list by applying a condition

12
In the figure, (a) generates a list of squares of the integers in list [1, 2, 3]. In (b), squares are
generated for each value in range(5). In (c), only positive elements of list nums are included in the
resulting list. In (d), a list containing the character encoding values in the string 'Hello' is created.
Finally, in (e), tuple vowels is used for generating a list containing only the vowels in stringw.

TUPLES:
A tuple is a sequence of values enclosed in parenthesis. The values can be any type. Tuples are
immutable. The values of the tuple cannot be changed.
Creating a tuple:
The tuples can be created by placing elements inside parenthesis separated by commas and
assigned to a variable.
Syntax: tuplevariablename=(value1,value2,…value
n) Example:
t=(1,2,3,4)
t1=(“a”,1,2,3,”hello”)
t3=(“Python”,[1,2,3])
t4=(10,) #tuple with single element
Accessing values in tuple:
In order to access the values in a tuple, it is necessary to use the index number enclosed in
square brackets along with the name of the tuple.
Example:
t1=(1,”python”,10,20)
t1[1] will access the value “python” from the tuple t1

13
#Example using tuples
t1=(1,2,3,"python",10)
print(t1)
print(t1[3])
print(type(t1))
t2=(10)
print(type(t2))
#tuple with single element should end with a comma
t3=(10,)
print(type(t3))
print(t1[1:])
print(t1[-4:])
print(t1[1:4])
OUTPUT:
(1, 2, 3, 'python', 10)
python
<class 'tuple'>
<class 'int'>
<class 'tuple'>
(2, 3, 'python',10)
(2, 3, 'python',10)
(2, 3, 'python')
TUPLES ARE IMMUTABLE:
Tuples are immutable. The elements of the tuple cannot be changed.
Example:
#Example to show tuples are
immutable list1=[10,20,30]
print(list1)
list1[0]=100
print(list1)
t1=(1,2,3,"python",10)
print(t1)
t1[0]=10
print(t1)
14
Output:
[10, 20, 30]
[100, 20, 30]
(1, 2, 3,'python', 10)
t1[0]=10
TypeError: 'tuple' object does not support item assignment

Basic Tuples Operations

Built-in Tuple Functions:


Python includes the following tuple functions-

methods example description


a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the first
>>> a.index(5) 4 matched item.

15
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the given
>>> a.count(3) 1 element.

len(tuple) >>> len(a) 5 return the length of the


tuple
min(tuple) >>> min(a) 1 return the minimum
element in a tuple
max(tuple) >>> max(a) 5 return the maximum
element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.

TUPLE ASSIGNMENT:
Tuple assignment allows the assignment of values to a tuple of variables on the left side of
the assignment from the tuple of values on the right side of the assignment. The number of
variables in the tuple on the left of the assignment must match the number of elements in the
tuple on the right of the assignment. The left side is a tuple of variables; the right side is a tuple
of expressions. Each value is assigned to its respective variable. All the expressions on the right
side are evaluated before any of the assignments.
Example 1 :
>>> a=("aaa",101,"cse") #tuplepacking
>>> (name,no,dept)=a #tupleunpacking
>>> a
('aaa', 101, 'cse')
>>>name 'aaa'
>>>no 101
>>> dept 'cse'
With the help of tuple assignment, the variables name, no, dept are assigned in one-line statement.
Example 2:
Swapping of two values using tuple assignment
#Example for swapping two values using tuple assignment
a=10
b=20
print("Before swapping",a,b)
a,b=b,a
print("After swapping",a,b)
Output:
Before swapping 10 20
After swapping 20 10
In the above example, the values of two variables are swapped without using third variable,
using tuple assignment

TUPLES AS RETURN VALUES:


A function can only return one value. If the return value is a tuple, then a function can return
multiple values.
16
Example 1:
The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder. Here the result is stored as a tuple
#Tuple as return values
t=divmod(7,3)
print(t)
Output:
(2, 1)
Tuple assignment can be used to store the elements separately.
#Tuple assignment store the elements
quot,rem=divmod(7,3)
print(quot)
print(rem)
Output:
2
1
Example 2:
To return a tuple of values max and min are built-in functions that find the largest and smallest elements of a
sequence. min_max computes both and returns a tuple of two values.
#Tuple as return values
def min_max(t):
return
min(t),max(t)
t=[1,2,20,40,50]
a,b=min_max(t)
print("The minimum value",a)
print("The maximum value",b)
Output:
The minimum value 1 The
maximum value 50

DICTIONARIES
A Dictionary is a collection of items are separated by commas, enclosed in curly braces {}. A dictionary
contains a collection of indices, which are called keys, and a collection of values. Each key is associated
with a single value. The association of a key and a value is called a key value pair or sometimes an item. A
dictionary represents a mapping from keys to values
Properties of dictionaries:
1. Dictionaries are mutable
2. Keys are unique within a dictionary
3. Values can be duplicate
4. The values of a dictionary can be of any type
5. The keys must be of an immutable data type such as strings, numbers, or tuples
Uses:
Dictionaries are used when there is
1. Need for a logical association between a key-pair value 2.Need
for fast lookup of data using custom key
3. Data that is constantly modified
Properties of keys:
1. Keys must be unique. Keys cannot duplicate
2. Keys must be of immutable type such as numbers, string, tuple
17
Example:
#properties of keys
d1={1:1,'name':'John','name':'Asha'}
print(d1)
print(d1['name'])
d2={[1]:"hello"}
print(d2)

Output:
{1: 1, 'name':
'Asha'} Asha
Traceback (most recent call last):
d2={[1]:"hello"}
TypeError: unhashable type: 'list'

Creating a Dictionary
1. A dictionary can be created as follows:
Syntax:
dictionary name={key1:value1,key2:value2,….,keyn:value n}
Examples:
Empty dictionary: { } Dictionary with integer keys
d={1:‟red‟,2:‟yellow‟,3:‟green‟}
d1={“name‟:‟xxxx‟,3:[“Hello‟,2,3]}

2. The function dict() creates a new dictionary.

EXAMPLE:
#Creating a dictionary
d={1:'red',2:'yellow',3:'green'}
print(d)
#Creating a dictionary using dict()
d1=dict(one=1,two=2,three=3)
print(d1)
Output
{1: 'red', 2: 'yellow', 3: 'green'}
{'one': 1, 'two': 2, 'three': 3}

ACCESSING ELEMENTS IN A DICTIONARY

The elements of the dictionary are accessed by using keys of the dictionary. The elements of
the dictionary are accessed by association not by index. The elements of the dictionary can also be
accessed using get()
Example using keys:
d1={1:1,2:8,3:27,4:64,5:125}
For example to access the value 64 form the dictionary, d1[4] will get the value 64

18
Example using get()
Syntax:
dictname.get(key,default) d1.get(4)
will access the value 64
If the key is not present in the dictionary, then get() returns none. If key is not present in the dictionary,
default value will be returned if given in get()
EXAMPLE:
#Creating and accessing the dictionary
d={1:1,2:8,3:27,4:64,5:125}
print("the creation of dictionary by assignment",d)
d1=dict(one=1,two="python")
print("the creation of dictionary by dict()",d1)
print("Accessing by using key",d[1])
print("Accessing by using key",d1['one'])
print("Accessing by get()",d.get(4))
print("Accessing by using get()",d1.get('two'))
print("get() with default value",d1.get('three',0))
print("get() method with none as default",d1.get('three'))
print("get() method with default",d1.get('three',3))
Output:
the creation of dictionary by assignment {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
the creation of dictionary by dict() {'one': 1, 'two': 'python'}
Accessing by using key 1
Accessing by using key 1
Accessing by get() 64
Accessing by using get() python
get() with default value0
get() method with none as default None
get() method with default3

DICTIONARY OPERATIONS
Dictionaries are mutable datatypes in python. The following operations are possible on dictionaries:

1. Updating a dictionary
The values in a dictionary can be changed ,added or deleted. If the key is present in the
dictionary, then the associated value with key is updated or changed ,otherwise a new key:value
pair is added
Example:
#Dictionary updation
d={'name':'John','age':27}
print(d)
d['age']=30
print(d)
d['address']='brazil'
print(d)
19
Output:
{'name': 'John', 'age':27}
{'name': 'John', 'age':30}
{'name': 'John', 'age': 30, 'address': 'brazil'}
When the value of age is changed, the interpreter searches for key “age” in the dictionary and
changes its value.
When d[“address”] is executed, the interpreter does not find the key “address” in the dictionary,
hence a new key:value pair is added
2. Deleting elements from dictionary
The elements can be removed or deleted from a dictionary by using
pop(),popitem(),clear(),del keyword

pop(): Removes an element from the dictionary for which the key is provided
popitem(): Removes or deletes and returns an arbitary element from the dictionary.
clear(): Removes all the elements from the dictionary at once.
del: Deletes the entire dictionary
Example:
#Dictionary Deletion
cubes={1:1,2:8,3:27,4:64,5:125,6:216}
print(cubes)
print("deletion using pop()",cubes.pop(6))
print("deletion using popitem()",cubes.popitem())
print("deletion using clear()",cubes.clear())
del cubes
print(cubes)
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
deletion using pop() 216
deletion using popitem() (5, 125)
deletion using clear()None
NameError: name 'cubes' is not defined
3. Traversal:
Traversal in dictionary is done on the basis of keys. For traversal, for loop is used which iterates
over the keys in the dictionary and prints the corresponding values using keys

#Dictionary traversal
cubes={1:1,2:8,3:27,4:64,5:125}
for i in cubes:
print(i,cubes[i])
Output:
11
28
3 27
4 64
5 125
20
4. Membership
Using the membership operators in and not in, whether a key is present in the dictionary or not
can be tested. If the key is present in the dictionary the in operator returns True other False. The
not operator returns True if the key is not present in the dictionary, False otherwise

Example:
#Dictionary membership
cubes={1:1,2:8,3:27,4:64,5:125}
print(1 in cubes)
print(27 in cubes)
print(27 not in cubes)
Output:
True
False
True

DICTIONARY FUNCTIONS
Python includes the following dictionary functions-
cmp(dict1, dict2)
The method cmp() compares two dictionaries based on key and values.
Syntax:
cmp(dict1, dict2)
Parameters
dict1 -- This is the first dictionary to be compared with dict2.
dict2 -- This is the second dictionary to be compared with dict1.

Return Value
This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2, and 1 if dict1> dic2.

Sorted(dictname):
It returns the sorted list of keys
len(dictname):
The method len() gives the number of items in the dictionary.
Syntax:
len(dict)
str(dict)
The method str() produces a printable string representation of a dictionary.
Syntax
str(dictname)
type()
The method type() returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.
Syntax
Following is the syntax for type()
method: type(dictname)

21
Example:
#dictionary functions
dict1 = {'Name': 'Zara', 'Age': 7}
print(sorted(dict1))
print(len(dict1))
a=(str(dict1))
print(a)
print(type(a))
print(type(dict1))
Output:
['Age', 'Name'] 2
{'Name': 'Zara', 'Age': 7}
<class 'str'>
<class 'dict'>

DICTIONARY METHODS:

S.no Method Description


1. dict.clear() Removes all elements of dictionary at once

2. dict.copy() Returns a copy of dictionary dict

3. dict.fromkeys() It Create a new dictionary with keys from sequence and


values set to value.
4. dict.get(key, For the key passed as parameter, returns value or
default=None) default if key not in dictionary

5. dict.items() Returns a list of (key, value) pairs of the dictionary

6. dict.keys() Returns list of all keys in the dictionary

7. dict.setdefault(key Similar to get(), but will set dict[key]=default if key is


, default=None) not already in dict

8. dict.update(dict2) It adds the items from dict2 to dict


9. dict.values() It returns all the values in the dictionary

dict.clear():
This method is used to remove all the items from the dictionary. This method does not return
any value
Syntax:
dictname.clear()

Example:
#Dictionary method clear()
d={1:1,2:8,3:27,4:64,5:125}
22
print(d)
d.clear()
print(d)
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
{}
dict.copy():
This method returns a copy of the dictionary.
Syntax:
dictname.copy()
Example:
#Dictionary method copy()
d={1:1,2:8,3:27,4:64,5:125}
print(d)
c=d.cop
y()
print(c)
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5:125}
{1: 1, 2: 8, 3: 27, 4: 64, 5:125}
dict.fromkeys():
This method creates a new dictionary with keys from seq and values set to value. This
method returns the list.
Syntax:
dictname.fromkeys(seq[, value]))

Parameters
seq - This is the list of values which would be used for dictionary keys
value - This is optional, if provided then value would be set to thisvalue
Example:
#Dictionary method fromkeys()
d={1:1,2:8,3:27,4:64,5:125}
print(d)
c=d.fromkeys([1,2,3],"python")
print(c)
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
{1: 'python', 2: 'python', 3: 'python'}

dict.get(key, default=None)
The method get() returns a value for the given key. If the key is not available then returns default
value None. This method returns a value for the given key. If the key is not available, then returns
default value as None.
Syntax:
dict.get(key, default=None)

23
Parameters
key - This is the Key to be searched in the dictionary.
default - This is the Value to be returned in case key does not exist.
Example:
#Dictionary method get()
d={1:1,2:8,3:27,4:64,5:125}
print(d)
print("The value at key 2 is",d.get(2))
print("The value at key 6 is",d.get(6))
print("The value at key 6 is",d.get(6,216))
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
The value at key 2 is 8
The value at key 6 is None
The value at key 6 is 216
dict.items():
This method items() returns a list of dict's (key, value) tuple pairs.
dict.items()
Example:
#Dictionary method items()
d={1:1,2:8,3:27,4:64,5:125}
print(d)
print("The items in the dictionary is",d.items())
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
The items in the dictionary is dict_items([(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)])
dict.keys():
This method returns a list of all the available keys in the dictionary
Syntax:
dict.keys()
Example:
#Dictionary method keys()
d={1:1,2:8,3:27,4:64,5:125}
print(d)
print("The items in the dictionary is",d.keys())
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
The items in the dictionary is dict_keys([1, 2, 3, 4, 5])
dict.setdefault():
This method is similar to get(), but will set dict[key]=default if the key is not already in dict.
This method returns the key value available in the dictionary and if given key is not available
then it will return provided default value.
Syntax:
dict.setdefault(key, default=None)
Example:

24
#Dictionary method setdefault()
d={1:1,2:8,3:27,4:64,5:125}
print(d)
print("The value at keyis",d.setdefault(6))
print(d)
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
The value at key is None
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: None}
dict.update(dict2)
The method adds dictionary dict2's key-values pairs in to dict. This function does not return
anything. This method does not return any value.
Syntax:
dict.update(dict2)
Example:
#Dictionary method update()
d1={1:1,2:8,3:27,4:64,5:125}

print(d1) d2={"one":"python","two":"python","three":"python"} print(d2)


d2.update(d1)
print(d2) Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
{'one': 'python', 'two': 'python', 'three': 'python'}
{'one': 'python', 'two': 'python', 'three': 'python', 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

dict.values()
The method values() returns a list of all the values available in a given dictionary.
Syntax:
dict.values()
Example:
#Dictionary method values()
d={1:1,2:8,3:27,4:64,5:125}
print(d)
print("The value at key is",d.values())
Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
The value at key is dict_values([1, 8, 27, 64, 125])

HISTOGRAM

A histogram a graphical representation of a frequency distribution of some numerical data. A


histogram is an accurate graphical representation of the distribution of numerical data. It takes as
input one numerical variable only. The variable is cut into several bins, and the number of
observations per bin is represented by the height of the bar.

25
#To draw a histogram for incomes import
matplotlib.pyplot as plt import numpy as np
income=[2000,3100,2500,2400,3000]
numbins=5 plt.hist(income,numbins,facecolor="GREEN",alpha=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title("Example histogram for incomes")
plt.legend()
plt.show()

Output:

The pyplot.hist() method is used for generating histograms, and will automatically select the
appropriate range to bin our data. With axis labels, a title, and the show() method are used to
display the histogram. It works by taking a list of numbers, binning those numbers within a
number of ranges, and counting the number of occurrences in each bin.
The hist() function has many options to tune both the calculation and the display; here's an
example of a more customized histogram:
plt.hist(data, bins=30, normed=True,
alpha=0.5, histtype='stepfilled',
color='steelblue', edgecolor='none');

Keywords for the hist() function:


bins: number of bins you want to have. can also be a list of bin edges.

26
range: lower and upper range of the bins
normed: “= True” means you get a probability distribution instead of just raw number
counts histtype: ʻbarʼ= traditional stype, ʻstepʼ= a line plot.
Weights: this is an array of values that must have the same size as the number of
bins label = “whatever you want to call these data points/lines”.
plt.legend()and python will make your legend

#Example for gaussian histogram


import matplotlib.pyplot as plt from
numpy.random
import normal
gaussian_numbers=normal(size=1000)
#income=[2000,3100,2500,2400,3000]
#numbins=6
plt.hist(gaussian_numbers,facecolor="YELLOW",alpha=0.5)
plt.xlabel('Value')
plt.ylabel('Frequency') plt.title("Example
gaussian histogram") plt.legend()
plt.show()
Output:

In above example the data used is 1000 random number drawn from a Gaussian distribution.

27
Example2:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 20
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5) # add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$') # Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()
OUTPUT:

PART - A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a.List=[‘p’,’r’,’i’,’n’,’t’,]
b. Print list[8:]
4. Give the syntax required to convert an integer number into string?
5. List is mutable. Justify?
28
6. Difference between del and remove methods in List?
7. Difference between pop and remove in list?
8. How are the values in a tuple accessed?
9. What is a Dictionary in Python?
10. Define list comprehension
11. Write a python program using list looping
12. What do you meant by mutability and immutability?
13. Define Histogram.
14. Define Tuple and show it is immutable with an example.
15. State the difference between aliasing and cloning in list.
16. What is list cloning?
17. What is deep cloning?
18. State the difference between pop and remove method in list.
19. Create tuple with single element.
20. Swap two numbers without using third variable.
21. Define properties of key in dictionary.
22. How can you access elements from the dictionary?
23. Difference between delete and clear method in dictionary.
24. What is squeezing in list? Give an example.
25. How to convert a tuple in to list?
26. How to convert a list in to tuple?
27. Create a list using list comprehension.
28. Advantage of list comprehension.
29. What is the use of map () function.
30. How can you return multiple values from function?
31. What is sorting and types of sorting?
32. Find length of sequence without using library function.
33. How to pass tuple as argument?
34. How to pass a list as argument?
35. What is parameter and types of parameter?
36. How can you insert values in to dictionary?
37. What is key value pair?
38. Mention different data types can be used in key and value?
39. What are the immutable data types available in python?
40. What is the use of from keys() in dictionary?

29
PART-B
1. Explain in details about list methods.
2. Discuss about operations in list.
3. What is cloning? Explain it with example.
4. What is aliasing? Explain with example.
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples.
7. Write a program for matrix multiplication
8. Write a program for matrix addition.
9. Write a program for matrix subtraction.
10. Write a program for matrix transpose.
11. Write procedure for selection sort.
12. Explain merge sort with an example.
13. Explain insertion with example.
14. Explain in detail about dictionaries and its methods.
15. Explain in detail about advanced list processing.
University Questions
PART-A
1. What is list ? How lists differ from tuples?
2. How to slice a list in Python?
3. Relate strings and lists.
4. Give a-function that can take a value and return the first key mapping to that value in a
dictionary.
PART-B
1. What is a dictionary in Python ? Give example.
2. Appraise the operations for dynamically manipulating dictionaries. 3.Write a
Python program to perform linear search on a list.(8)
4. Write a Python program to store “n” numbers in list and sort the list using selection sort.
5. Discuss the different options to traverse a list.
6. Demonstrate the working of +, * and slice operators in python.
7. Compare and contrast tuples and lists in Python.
8. Write a script in Python to sort n numbers using selection sort.

30

You might also like