Python 2 (A)
Python 2 (A)
RV College of
Engineering
Dept of Mech. Engg.
List in Python
RV College of Go, change the world
Engineering List in Python
List is a sequence of data type called items or elements. The elements can be any
data type (integer, float, string, etc).
List are mutable, meaning, their elements can be changed.
A list is created by placing all the elements (items) inside a square bracket [],
separated by commas. E.g. variable Name = [index]
a,b,c = [],[23,45,6,78,78],[1,'Hello',3,4]
print (a,b,c)
L1,L2 = [10,20,30], ['Rama','Krishna','Govinda']
print (L1,'\n',L2)
L1,L2 = [10,20,30], ['Rama','Krishna','Govinda']
print (L1,'\n',L2)
L3 =L1+L2
print (L3)
RV College of Go, change the world
Engineering List in Python-Indexing
Positive value of index means counting forward from beginning of the list (starts with zero)
Negative value means counting backward from end of the list. (starts with -1)
L1 = [45,60,70,80,90]
It can be access in several ways
Use the index operator[] to access an item in a list. Index starts from 0. So a list having 5
elements will have index from 0 to 4.
Forward Indexing Element Backward indexing
0 45 -5
1 60 -4
2 70 -3
3 80 -2
4 90 -1
num= [10,20,30,40,50,60,70] a = [[23,45,6,78,78],[1,'Hello',3,4]]
print (num) print(a[1][1])
print (num[0], num[1]) List = ['K','R','I','S','H','N','A']
print (num[-1], num[-2]) print(List[6])
RV College of Go, change the world
Engineering Adding Elements (append(), extend(), insert())
append (): Method of adds a single item (any data) to the end of existing list.
It modifies the original list. Syntax: list.append(items)
def sum_list(items):
sum_num=0.0
for i in items:
sum_num+=i
return sum_num
list=[]
n = int (input ("Enter the number of list elements:"))
for i in range (0,n):
print ("Enter the", i+1, "th element of list")
m =int (input())
list.append(m)
print (list)
print ("sum of list is=", sum_list(list))
RV College of Go, change the world
Engineering Program in List-2
Write a Python program to get the largest number from a list
def max_list(items):
max1 = max (items)
return max1
list=[]
n = int (input ("Enter the number of list elements:"))
for i in range (0,n):
print ("Enter the", i+1, "th element of list")
m =int (input())
list.append(m)
print (list)
print ("Maximum element is =", max_list(list))
RV College of Go, change the world
Engineering Program in List-3
Write a Python function that takes two lists and returns True if they have at least one common member.
def common_data(x,y):
result =False
for i in x:
for j in y:
if i==j:
result = True
return result
L1 = [2,3,4,5,6,7,8,9,10]
L2 = [1,11,12,13,14,15,8,9,19]
L3 = [200,201,202,203,204]
print (common_data(L1,L2))
print (common_data (L2,L3))
RV College of Go, change the world
Engineering Program in List-4
Write a Python program to generate and print a list of first and last 5 elements where the values are
square of numbers between given numbers (both included).
list=[]
n = int (input ("Enter the number of list elements:"))
for i in range (0,n):
print ("Enter the", i+1, "th element of list")
m =int (input())
list.append(m)
print (list)
print (multi_list(list))
RV College of Go, change the world
Engineering Program in List-7 &8
Write a Python program to generate a 3*4*6 3D array whose each element is *
array = [[['*' for col in range(6)]for col in range(4)] for row in range (3)]
print (array)
Write a Python program to convert a list of characters into a string
s = ['K','R','i','S','H','N',"A"]
print (''.join (s))
RV College of Go, change the world
Engineering
Tuple
RV College of Go, change the world
Engineering Tuple in Python
A tuple is a sequence of values, which can be of any type and they are indexed by
integer. Tuples are just like a list, but we can’t change vales of tuple in place. They are
immutable
They are created using Parentheses, rather than square bracket
Generally tuple is used for heterogeneous (different) datatypes and list for
homogeneous (similar) datatype
Since tuple are immutable, iterating through tuple is faster than with list. So there is a
slight performance boost.
Tuple that contain immutable elements can be used as key for a dictionary. With list,
this is not possible
If you have data that does not change, implementing it as tuple will guarantee that it
remains write-protected.
The index value of tuple starts from 0
RV College of Go, change the world
Engineering Tuple in Python
Tuples Lists
The Items are surrounded in The items are surrounded in square
paranthesis () brackets[]
Tuples are immutable in nature Lists are mutable in nature
There are 33 available methods on There are 46 available methods on lists
tupples
The dictionary, we can create keys In dictionary, we can’t use list as keys
using tuples
Fast Slow
Need Less Memory Need More Memory
Less Method More Method
RV College of Go, change the world
Engineering Tuple in Python
A tuple is created by placing all the items (elements) inside a parentheses() separated
by comma
The parentheses are optional but is a good practice to write it
A tuple can have any number of items and they may be different types (integer, float,
list, string, etc)
a = ()
b=(1,2,3,4,5,6,7,8)
c= (1,2,3,"rama","krishna",[1,2,3])
print ('a=',a, '\nb=',b,'\nd=',c)
RV College of Go, change the world
Engineering Tuple in Python-Accessing Elements
You can access the values in the tuple with their index, just as your did with lists;
Nested tuple are accessed using nested indexing
Negative indexing can be applied to tuples similar to lists
We can access a range of items in a tuple by using the slicing opetor
Trying to reassign a values in a tuple causes a typeerror
c=('Ramakrishna', [10,20,30],[56,78,90],'rvce')
c= (1,2,3,"rama","krishna",[1,2,3]) print (c[1][1])
print (c[0]) print (c[2][1])
print (c[-1]) print (c[2])
print (c[0]-c[1]) print (c[3])
c=('Ramakrishna',10,20,30,56,78,90,'rvce')
for i in c:
print (i)
RV College of Go, change the world
Engineering Tuple in Python-Changing Tuples
c=('Ramakrishna',10,20,30,56,78,
Unlike lists, tuples are immutable 90,'rvce')
a = ((1,2,3,4)+(5,6,7,8)) print (c[1])
print (a) c[1]=20
print [c[1]]
This means that elements of a tuple cannot be changed once it has been assigned. But,
it the element is itself a mutable datatype like list, its nested items can be changed.
c=('Ramakrishna',[10,20,30,56,78,90],'rvce')
a= (1,2,3,4) print (c[1][1])
b=(5,6,7,8) c[1][1]=30
c=a+b print (c)
print (c)
Concatenation : we can use + operator to combine tow tuples
Repeat: we can also repeat the elements in a tuple for a given number of time using the
operator (+ and *)
print (('Bangalur ')*4)
RV College of Go, change the world
Engineering Tuple in Python-Deleting Tuples
We cannot change the element in a tuple, that also means we cannot delete or remove
items from a tuple
a= (1,2,3,4) a= (1,2,3,4)
b=(5,6,7,8) del (a(1))
c=a+b
delete (c)
But deleting a tuple entirely is possible the keyword del.
a= (1,2,3,4)
print(a)
del (a)
print (a)
RV College of Go, change the world
Engineering Tuple in Python-Python Tuple Methods
Methods that add items or remove items are not available with tuple. Only the
following two methods are available
Count(): Return the number of items that is equal to x
Index(): Return index of first item that is equal to x
a =(1,2,3,4,5,5,6,7,5,8,6,5,4,3,5,6,7)
print ('Total number of 5s=', a.count(5))
print ("Position of 8 is = ", a.index(8))
RV College of Go, change the world
Engineering Tuple in Python- tuple Membership test
We can test if an items exists in a tuple or not using the keyword in
fruits = ('apple', 'Orange', 'Banana', 'Mango')
if 'apple' in fruits:
print ('Yes, Apple in the fruits ')
any(): Return True if any element of the tuple is true. If the tuple is empty, return False
a,b,c,d =(1,2,3,4,0),(0,False),(0,False,5),()
print (any(a),'\n',any(b),'\n',any(c),'\n',any(d))
RV College of Go, change the world
Engineering
Tuple in Python- Other functions
min(): The min() function returns the smallest item in an iterable. It can also be
used to find the smallest item between two or more parameters
max():The max() function returns the largest item in an iterable. It can also be
used to find the largest item between two or more parameters
len(): The len() function returns the number of items (length) in an object
sum(): The sum() function adds the items of an iterable and returns the sum
.
a =(1,2,3,4,5,5,6,7,5,-8,6,5,4,3,5,6,7)
print (min(a))
print (max(a))
. print (a)
print (len(a))
print (sum(a))
RV College of Go, change the world
Engineering
Time Tuple in Python
What is TimeTuple?
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below:
Inde
Field Values
x
0 4-digit year 2008
1 Month 1 to 12
2 Day 1 to 31
.
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 61 (60 or 61 are leap-seconds)
.
6 Day of Week 0 to 6 (0 is Monday)
7 Day of year 1 to 366 (Julian day)
8 .Daylight savings -1, 0, 1, -1 means library determines DST
.
RV College of Go, change the world
Engineering
Time Tuple in Python
The above tuple is equivalent to struct_time structure. This structure has following
attributes:
Index Attributes Values
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 . tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are leap-seconds)
.
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday 1 to 366 (Julian day)
8 tm_isdst -1, 0, 1, -1 means library determines DST
.
.
RV College of Go, change the world
Engineering
Time Tuple in Python
Getting current time
import time
a = time.localtime(time.time())
print("Local Current time:", a)
Getting formatted time -:
import time
. a = time.asctime(time.localtime(time.time()))
print("Local Current time:", a)
Getting calendar for a month
.
import calendar
cal = calendar.month(2023, 2)
print ("Here is the calendar")
. print (cal)
.
RV College of Go, change the world
Engineering
Sample Program in Tuple-1
Write a python program to unpack a tuple in several variable
a=(4,5,6,7)
print(a)
n1,n2,n3,n4 =a
print (n1,'+',n2,'+',n3,'+',n4,'=',n1+n2+n3+n4)
a=(4,5,6,7)
print(a)
a = a+ (10,)
print(a)
RV College of Go, change the world
Engineering
Sample Program in Tuple-1
Write a python program to add items in a specific index
aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print ("List elements : ", aList)
aList.append(345)
aTuple = tuple(aList)
print (aTuple)
a=('A','P','P','L','E')
print (a)
print (''.join(a))
RV College of Go, change the world
Engineering
Dictionaries in Python
RV College of Go, change the world
Engineering
Dictionaries in Python
List Tuple Dictionary
A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuple are fixed size in nature In values can be of any data type and can
repeat, key must be of immutable type
Lists are enclosed in brackets [] and there Tuples are enclosed in parenthesis () and Dictonary are enclosed in curly braces {}
elements and size can be changed cannot be updated and consist of key: value
Homogenous Heterogeneous Homogenous
E.g. List = [10,20.30] Words =(“Spam”, “eggs”) Dict= {“ram”:26, “Abi”: 28
Can contain duplicate element Can contain duplicate elements. Can’t contain duplicate keys but can
contain duplicate values
Slicing can be done Slicing can be done Slicing can’t be done
Usage: Usage: Usage:
List is used if a collation of data that Tuple can be used when data cannot be Dictionary is used when a logical
doesn’t need random access changed association between key value pair
List is used when data can be modified A tuple is used in combination with a When in need of fast lookup for data
frequently dictionary i.e tuple might represent a key based on a custom key
Dictonary is used when data is being
constantly modified
RV College of Go, change the world
Engineering
Dictionaries in Python
A dictionary is mutable and is another container type that can store any number of Python
objects, including other container types.
Dictionaries consist of pairs (called items) of keys and their corresponding values.
Python dictionaries are also known as associative arrays or hash tables. The general syntax
of a dictionary is as follows:
rvce={"krishna":"Professor", "Rajkumar": "Associate
Professor", "Shivaraj": "Assistance Professor"}
print (rvce)
print ("\nKrishna:",rvce["krishna"])
print ("\nRajkumar:",rvce["Rajkumar"])
Curley brackets are used to represent a dictionary.
Each pair in the dictionary is represented by a key and value separated by a colon.
Multiple pairs are separated by comas
RV College of Go, change the world
Engineering
Dictionaries in Python
A dictionary is an unordered collection of key value pairs.
A dictionary has a length, specifically the number of key value pairs.
A dictionary provides fast look up by key.
The keys must be immutable object types.
E.g.
mech={1:'one', 2:'Two', 3:'Three', 4:'Four’}
1, 2, 3, 4 are Keys and ‘One’, ‘’Two’, ‘Three’, ‘Four’ values
def creating_dic_device(device):
for i in device:
print (i, device[i])
dict.popitems(): similar to get(), but will set dict[key]=default if key is not already in dict
marks={'Maths': 46, 'Science': 43, 'English':40, 'Social': 39}
marks1={'Kannada':47, 'Hindi': 49, 'General Knowledge': 41}
marks.update(marks1)
print (marks)
marks.popitem()
print (marks)
marks.popitem()
print (marks)
RV College of Go, change the world
Engineering
Changing and Adding Dictionary
elements
Dictionaries are mutable. We can add new items or change the value of existing items using
an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
keys = []
values =[]
n = int (input("Enter the number of elements for dictonary:"))
print ("For Keys:")
for i in range (0,n):
element = input ("Enter the element"+ str(i+1)+ ":")
keys.append(element)
print ("For Values:")
for j in range (0,n):
element = int (input ("Enter the element"+str(j+1)+ ":"))
values.append(element)
d =dict(zip(keys,values))
print ("The dictionary is ", d)
Go, change the world
Dictionary –sample programs-3
RV College of
Engineering
Set in Python
RV College of Go, change the world
Engineering
Sets in Python
RV College of Go, change the world
Engineering
Sets in Python
RV College of Go, change the world
Engineering
Sets in Python
RV College of Go, change the world
Engineering Sets in Python
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be
immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
My_Set = {29,40,50,60}
print (My_Set)
a_set = {1,2,3,4,7,5,6,7,8,4,5,6,7,8}
print (a_set)
RV College of Go, change the world
Engineering
Sets in Python-Modifying a set in
Pythonindexing has no meaning.
Sets are mutable. However, since they are unordered,
import string
A = set(string.ascii_lowercase)
print (A)
B = {'a','b','c','d'}
C = {'x','y','z'}
print (A.issuperset(B))
print (C.issuperset(A))
print (A.issuperset(C))
RV College of Go, change the world
Engineering
Python Set other Operations
stop Required. An integer number specifying at which position to stop (not included).
Python provides inbuilt functions for creating, writing, and reading files.
There are two types of files that can be handled in python, normal text files and binary
files (written in binary language, 0s, and 1s).
Text files: In this type of file, Each line of text is terminated with a special character called
EOL (End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line, and the data is stored after
converting it into machine-understandable binary language.
# File Management
f =open("C:\\Users\\KRISHNA M\\Desktop\\Rama1.txt","a")
f.write("Bhima")
f.close()
RV College of
Engineering Create and Delete New file in python Go, change the world
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will be inserted at the end, after the
existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written will be inserted at the
end, after the existing data.
Delete a File: To delete a file, you must import the OS module, and run its os.remove() function:
# File Management
f=open ("C:\\Users\\KRISHNA M\\Desktop\\MK2.txt","a")
f.write ("\nR V College of Engineering")
# File Management-Delete
import os
. if os.path.exists("C:\\Users\\KRISHNA M\\Desktop\\Rama.txt"):
os.remove("C:\\Users\\KRISHNA M\\Desktop\\Rama.txt")
else:
print ("The file does not exist")
RV College of
Engineering Reading and writing text files in python Go, change the world
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the
file does not exists, raises the I/O error. This is also the default mode in which a file is opened.
# File Management
f=open ("C:\\Users\\KRISHNA M\\Desktop\\MK2.txt","r")
print (f.read())
Read Lines
.
RV College of
Engineering Reading and writing text files in python Go, change the world
Read Lines
f=open ("C:\\Users\\KRISHNA M\\Desktop\\MK2.txt","r")
print(f.readline())
Loop through the file line by line:
f=open ("C:\\Users\\KRISHNA M\\Desktop\\MK2.txt","r")
for i in f:
print (i)
Close File
f=open ("C:\\Users\\KRISHNA M\\Desktop\\MK2.txt","r")
for i in f:
print (i)
f.close()
.
RV College of
Engineering Sample Programs-1 Go, change the world
def file_read(fname):
txt=open(fname)
print (txt.read())
file_read ("C:\\Users\\KRISHNA M\\Desktop\\MK.txt")
.
RV College of
Engineering Sample Programs-3 Go, change the world
Combine each line from first file with the corresponding line in second file
#Combine each line from first file with the corresponding line in second file
with open("C:\\Users\\KRISHNA M\\Desktop\\MK.txt") as f1, open
("C:\\Users\\KRISHNA M\\Desktop\\MK1.txt") as f2:
. for line1, line2 in zip (f1, f2):
print (line1+line2)