100% found this document useful (1 vote)
305 views

Chapter 3: Structured Types, Mutability and Higher-Order Functions

This document discusses strings in Python. Some key points: - Strings represent a group of characters enclosed in single or double quotes. Common string methods include len(), find(), upper(), lower(), etc. - Strings are indexed and sliced like other sequences. Indexing starts from 0 and can be positive or negative. Slicing uses square brackets and a start:stop:step syntax. - Other string operations include concatenation, checking membership, comparison, stripping whitespace, and finding/extracting substrings. - Strings are immutable in Python - their values cannot be altered, only reassigned. This document provides examples of many common string operations in Python.

Uploaded by

devansh thaker
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
305 views

Chapter 3: Structured Types, Mutability and Higher-Order Functions

This document discusses strings in Python. Some key points: - Strings represent a group of characters enclosed in single or double quotes. Common string methods include len(), find(), upper(), lower(), etc. - Strings are indexed and sliced like other sequences. Indexing starts from 0 and can be positive or negative. Slicing uses square brackets and a start:stop:step syntax. - Other string operations include concatenation, checking membership, comparison, stripping whitespace, and finding/extracting substrings. - Strings are immutable in Python - their values cannot be altered, only reassigned. This document provides examples of many common string operations in Python.

Uploaded by

devansh thaker
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

L.J.

Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Chapter 3: Structured types, Mutability


and Higher-Order Functions
 Strings, Tuples, Lists and Dictionaries :

 Strings :
 String represents a group of characters.
 To create a string in python, assign a group of characters to a variable, should be
enclosed inside single quotes or double quotes:
Str1= ‗hello world‘
Str2= ―hello world‖
 Also we can use triple single quotes or triple double quotes while creating the string
to represent a string that occupies several lines:
Str3= ‗‘‘hello
World‘‘‘
Str4= ―‖‖hello
World‖‖‖
 To display substring inside string:
Str5= ‗I am ―python‖ program‘
Str6= ―I am ‗python‘ program‖
 To print a string:
print Str1
Output: hello world

 String Inbuilt functions:


Function Description Function Description
Name Name
len() Finding length of string capitalize() Returns the string whose first letter is
capital and remaining are lowercase
find() Gives the substring which isalnum() Returns true when a string contains
occurs in the give string all alphanumeric characters
lstrip() Function returns string by isalpha() Return the value when the strings
removing or stripping the consist of the alphabetic characters
characters from the beginning only otherwise returns false.
of the string. Default white
space
rstrip() Function returns a string by isdigit() Return the true value if the string
removing or stripping the contains only digits.
characters from the end of the
string. Default white space
Strip() Function returns a string by lower() Gives the string in a lower case
removing or stripping the letters

Python Programming (LJIET - 8-CE/IT Dept) 2018 1


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

characters from the beginning


and end of the string. Default
white space
isspace() Used to check that a string islower() Used to check that all the letter in a
contains only white space or not given string are in a lowercase.
replace() Used to replace the old value upper() Gives the string in a upper case
with the new value of the string letters
join() Used to join the string elements isupper() Used to check that all the letters in a
of sequence by using the str give string are in a upper case.
separator.
split() Used to split the string. Returns istitle() Used to check whether all the case
a list of all the words in the based characters in the string
string following non case base letters are
uppercase and all other case based
characters are lower case.
count() Returns the number of swapcase() Swaps the character case. Means it
occurrences of substring in a converts uppercase string to lower
string. case and vice versa.

 Length of String:
The length of the string represents the number of characters in a string. We use len()
function. This function gives the number of characters including spaces in the string
str='core python'
n=len(str)
print (n)
Output: 11

 Indexing in String:
Index represents the position number. They are written using square braces [ ]. By
specifying the index we can refer individual elements.
Str[i] represents ith element of string. Positive index starts from left to right and
negative index starts from right to left (end of the string).
str='core python'
n=len(str)
i=0
while i<n: #access string using positive indexing
print(str[i], end=" ")
i+=1
print("\n---------------------------------------------------")
i=-1
while i>=-n: #access string using Negative indexing
print(str[i], end=" ")
i-=1

Python Programming (LJIET - 8-CE/IT Dept) 2018 2


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

print("\n---------------------------------------------------")

for i in str: #prints each character in new line


print (i,end=" ")
print("\n---------------------------------------------------")
for i in str[::]: #anoter way to use
print (i,end=" ")
print("\n---------------------------------------------------")
for i in str[::-1]: #reverse order
print (i,end=" ")

Ouput:
core python
---------------------------------------------------
nohtyp eroc
---------------------------------------------------
core python
---------------------------------------------------
core python
---------------------------------------------------
nohtyp eroc

 Slicing in String:
Slice represents a part or piece of a string.
Syntax: stringname [ start : stop : stepsize ]
str='core python'
print (str[0:9:1]) #accessing strting from 0th to 8th element in steps of 1
print (str[0:9:2]) #accessing strting from 0th to 8th element in steps of 2
print (str[::]) #access string from start to last charcter
print (str[2:4:1]) #accessing strting from str[2] to str[4] element in steps of 1
print (str[::2]) #accessing entire strting in steps of 2
print (str[::-1]) #reverse the string
Output:
core pyth

Python Programming (LJIET - 8-CE/IT Dept) 2018 3


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

cr yh
core python
re
cr yhn
nohtyp eroc
 Repeating in String:
str='core python'
print (str*2)
s=str[5:7]*3
print(s)
Output:
core pythoncore python
pypypy
 Concatenation of String:
str1='core python'
str2="programs"
str3=str1+str2
print (str3)
Output:
core pythonprograms

 Checking membership of String:


str1="this is a string"
sub="is"
if sub in str1:
print ("sub string is found in main string")
else:
print ("sub string is not found in main string")
Output:
sub string is found in main string

 Comparing Strings:
str1="Box"
str2="box"
if(str1==str2):
print ("both are same")
else:
print ("both are not same")

Python Programming (LJIET - 8-CE/IT Dept) 2018 4


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Output:
both are not same

 Removing Spaces from a Strings:


str1=" core python "
print (str1.rstrip()) #remove space at right
print (str1.lstrip()) #remove space at left
print (str1.strip()) #remove space from both sides
Output:
core python
core python
core python

 Finding Sub Strings:


find(), index(), rfind() and rindex() methods return the location of the first occurrence
of the sub string in the main string.
find() and index() : searches from the beginning of the main string. Find() returns -1 if
the sub string is not found in the main string. The index() method returns
‗ValueError‘ exception if the sub string is not found.
rfind() and rindex() : searches from the ending of the main string.

Syntax: mainstring.find(substring, beinning, ending)

main_str= raw_input('Enter the main string:')


sub_str= raw_input('Enter the sub string:')

n = main_str.find(sub_str,0,len(main_str))

if n == -1:
print "sub string is not found"
else:
print "sub string found at position:", n+1

Syntax: mainstring.index(substring, beinning, ending)

Python Programming (LJIET - 8-CE/IT Dept) 2018 5


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

main_str= raw_input('Enter the main string:')


sub_str= raw_input('Enter the sub string:')
try:
n = main_str.index(sub_str,0,len(main_str))
except ValueError:
print "sub string is not found"
else:
print "sub string found at position:", n+1

python program to find all position of sub string in main string:


main_str= raw_input('Enter the main string:')
sub_str= raw_input('Enter the sub string:')
i=0
flag=False
n=len(main_str)
while i<n:
pos = main_str.find(sub_str,i,n)
if pos!= -1:
print "Fund at position: ",pos+1
i=pos+1
flag=True
else:
i=i+1
if flag == False:
print "sub string is not found"

Python Programming (LJIET - 8-CE/IT Dept) 2018 6


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Another Way:
main_str= raw_input('Enter the main string:')
sub_str= raw_input('Enter the sub string:')
flag=False
pos = -1
n=len(main_str)
while True:
pos = main_str.find(sub_str,pos+1,n)
if pos == -1:
break
print "Found at position:", pos+1
flag = True
if flag == False:
print "sub string is not found"

 Counting Substrings in a string:


count() method will count the number of occurrence of a sub string in a main string.

Syntax: stringname.count(substring, beginning, ending)

string1= "New Delhi New Delhi New Delhi"


n = string1.count('New')
print n
n = string1.count('e',0,15)
print n
n = string1.count('e',0,len(string1))
print n
Output:
3
3
6

 String are immutable:


An immutable object is an object whose content cannot be changed.
str1="Alpa"
print str1[0]
str1[0]='b'

Python Programming (LJIET - 8-CE/IT Dept) 2018 7


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 Replacing string with another string:


The replace() method is useful to replace a sub string in a string with another sub
string.

Syntax: stringname.replace(old,new)
str1="this is old string"
s1="old"
s2="new"
str2= str1.replace(s1,s2)
print str1
print str2

 Split() of string:
The split() method is used to brake a string into pieces. These pieces are returned as a
list. In split() method the argument, separator that represents where to separate or cut
the string.
Syntax : stringname.split(separator)
str1= "One, Two, Three, Four"
str2= str1.split(',')
print str2
Output:
['One', ' Two', ' Three', ' Four']

Program to count the no of words in a given string.


str1=raw_input("Enter the strig:")
n=len(str1.split())
print "no of words in a given string is:", n

Python Programming (LJIET - 8-CE/IT Dept) 2018 8


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 join() of string:
When a group of strings are given, it is possible to join them all and make a single
string. For this join method is used:
Syntax: separator.join(str)
Where separator represents the character to be used between the strings in the output.
‗str‘ represents a tuple or list of strings.

str1=('one','two','three')
str2='-'.join(str1)
print str2
str1=['hello','world','this','is','python']
sep=" "
str2=sep.join(str1)
print str2
Output:

 Changing case of a string:


There are four methods to change the case of a string:
str.upper() : convert all characters of a string into uppercase.
str.lower() : convert all characters of a string into lowercase.
str.swapcase() : convert all capital characters of a string into small and vice versa
str.title() : convert the string such that each word in the string will start with a capital
letter and remaining will be small letters.

str1="pYthon pRograMming"
print str1.upper()
print str1.lower()
print str1.swapcase()
print str1.title()

 Checking Starting and Ending of a string:


The startswith() method is useful to know whether a string is starting with a sub string
or not and to check the ending of a string, endswith() method is used.

Syntax: str.startswith(substring), str.endswith(substring)

Python Programming (LJIET - 8-CE/IT Dept) 2018 9


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

str1="This is python"
print str1.startswith('This')
print str1.startswith('The')

print str1.endswith('python')
print str1.endswith('program')

 Sorting of a string:
We can sort a group of strings into alphabetical order using sort() method and sorted()
function.
Syntax: str.sort(), str1=sorted(str)
str1=[]
n=int(raw_input('How many Strings?'))
for i in range(n):
print "Enter the string:"
str1.append(raw_input())
str2 = sorted(str1)
print "Ascending order sorted list:"
for i in str2:
print i
print '\n'
print "Descending order sorted list:"
str2 = sorted(str1, reverse=True) #for descending order
for i in str2:
print i

Python Programming (LJIET - 8-CE/IT Dept) 2018 10


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 String Testing Methods:

print "alpa2018 is alphanumeric: ", "alpa2018".isalnum()

print "alpa is alphabetic: ", "alpa".isalpha()

print "2018 is digit:", "2018".isdigit()

print "ALPA has all lowercase character:", "ALPA".islower()

print "ALPA has all uppercase character:","ALPA".isupper()

print "Alpa Rupala has all title case:","Alpa Rupala".istitle()

print "Alpa Rupala has all spaces:","Alpa Rupala".isspace()

print " has all spaces:"," ".isspace()

 Basically String is also a structured type data types, but other than this we will learn 3
types: Tuples, list and dict.

 Lists:
 List is an ordered sequence of values, where each value is identified by an index.
 In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
 It can have any number of items and they may be of different types (integer, float,
string etc.).

Python Programming (LJIET - 8-CE/IT Dept) 2018 11


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

# empty list
my_list = []
print(my_list)
# list of integers
my_list = [1, 2, 3]
print(my_list)
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
print(my_list)
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
print(my_list)

Output:
[]
[1, 2, 3]
[1, 'Hello', 3.4]
['mouse', [8, 4, 6], ['a']]

 List Index: We can 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.
my_list = ['l','j','i','e','t','s','g','h','y']
n_list = ["Happy", [2,0,1,5]]
odd = [2, 4, 6, 8]
print(my_list[0]) #indexing
print(my_list[2])
print(my_list[4])
print("negative indexing")
print(my_list[-1]) #negative indexing
print(my_list[-5])
print("nested indexing")
print(n_list[0][1]) #nested indexing
print(n_list[1][3])
print("slicing")
print(my_list[2:5]) #slicing
print(my_list[:-5])
print(my_list[5:])
print(my_list[:])
print("change element of list")
print(odd)
odd[0] = 1 #change element of list
print(odd)
odd[1:4] = [3, 5, 7]
print(odd)
print("append element to list")
odd.append(7) #append element
print(odd)
print("extend element to list")
odd.extend([9, 11, 13]) #extend element
print(odd)
print("+ operator to combine two lists")
print(odd + [9, 7, 5])
print("* operator repeats a list for the given number of times.")
print(["re"] * 3)
print("delete element of list")
del odd[2]
print(odd)

Python Programming (LJIET - 8-CE/IT Dept) 2018 12


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

del odd[1:5]
print(odd)
del odd
print(odd)

Output:
l
i
t
negative indexing
y
t
nested indexing
a
5
slicing
['i', 'e', 't']
['l', 'j', 'i', 'e']
['s', 'g', 'h', 'y']
['l', 'j', 'i', 'e', 't', 's', 'g', 'h', 'y']
change element of list
[2, 4, 6, 8]
[1, 4, 6, 8]
[1, 3, 5, 7]
append element to list
[1, 3, 5, 7, 7]
extend element to list
[1, 3, 5, 7, 7, 9, 11, 13]
+ operator to combine two lists
[1, 3, 5, 7, 7, 9, 11, 13, 9, 7, 5]
* operator repeats a list for the given number of times.
['re', 're', 're']
delete element of list
[1, 3, 7, 7, 9, 11, 13]
[1, 11, 13]
Traceback (most recent call last):
File
"C:/Users/Shefa20393/AppData/Local/Programs/Python/Python36/test.py
", line 40, in <module>
print(odd)
NameError: name 'odd' is not defined

 Creating list using range() : We can use the range() to generate a sequence of
integers which can be stored in a list.
lst=list(range(4,9,2))
print lst

Output:
[4, 6, 8]

 List Membership Test:


my_list = ['p','r','o','b','l','e','m']
print('p' in my_list)
print('a' in my_list)
print('c' not in my_list)

Python Programming (LJIET - 8-CE/IT Dept) 2018 13


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Output:
True
False
True

 Iterating Through a List


for fruit in ['apple','banana','mango']:
print("I like",fruit)

Output:
I like apple
I like banana
I like mango

 Updating elements of a list : Lists are mutable. It means we can modify the content
of a list. We can append, update or delete the elements of a list depending upon our
requirements.

 Python List In-built Methods:


Method Description Example
append() Add an element to the end of INPUT: lst=[0,1,2,3,4,5,6]
the list lst.append(9) #add new element
print lst
O/P: [0, 1, 2, 3, 4, 5, 6, 9]
extend() Add all elements of a list to lst.extend([3,6,8]) #add Multiple elements
the another list print lst
O/P: [0, 1, 2, 3, 4, 5, 6, 3, 6, 8]
insert() Insert an item at the defined lst.insert(5,10) #inserting element at particular
index index
print lst
O/P: [0, 1, 2, 3, 4, 10, 5, 6]
remove() Removes an item from the lst.remove(5) #removing by element
list print lst
O/P: [0, 1, 2, 3, 4, 6]
del() Delete an item at particular del lst[2] #removing by index
index print lst
O/P: [0, 1, 3, 4, 5, 6]
pop() Removes and returns an print lst.pop(5) #remove and return element at
element at the given index particulr index
O/P: 5
clear() Removes all items from the Works in third version only
list lst.clear()
print lst
O/P: []
Index() Returns the index of the first print lst.index(4)
matched item O/P: 4
count() Returns the count of number lst=[1,2,3,4,4,4]
of items passed as an print lst.count(4)
argument O/P: 3

Python Programming (LJIET - 8-CE/IT Dept) 2018 14


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

sort() Sort items in a list in lst1=[3,1,7,4,2]


ascending order lst1.sort()
print lst1
lst1.sort(reverse=True)
O/P: [1, 2, 3, 4, 7]
[7, 4, 3, 2, 1]
reverse() Reverse the order of items in lst.reverse() #reversing elements of list
the list print lst
O/P: [6, 5, 4, 3, 2, 1, 0]
copy() Returns a shallow copy of Works in third version only
the list l1=lst.copy()
print lst
print l1
O/P: [0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]

 Built-in Functions with List:


Function Description Example
all() Return True if all elements INPUT: lst1=[0,1,2,3,4,5,6]; lst2=[1,2,3]
of the list are true (or if the print all(lst1), all(lst2)
list is empty). O/P: False True
any() Return True if any element lst1=[0,1,2,3,4,5,6]; lst2=[0,0,0]
of the list is true. If the list print any(lst1), any(lst2)
is empty, return False. O/P: True False
enumerate() Return an enumerate object. lst1=[1,2,3,4]
print enumerate(lst1)
It contains the index and
print list(enumerate(lst1))
value of all the items of list
O/P: <enumerate object at 0x02A80058>
as a tuple [(0, 1), (1, 2), (2, 3), (3, 4)]
len() Return the length (the lst1=[1,2,3,4]
number of items) in the list. print len(lst1)
O/P: 4
list() Convert an iterable (tuple, set1={1,2,3,4}
string, set, dictionary) to a print list(set1)
list. O/P: [ 1, 2, 3, 4]
max() Return the largest item in lst1=[1,2,3,4]
the list. print max(lst1)
O/P: 4
min() Return the smallest item in lst1=[1,2,3,4]
the list. print min(lst1)
O/P: 1
sorted() Return a new sorted list lst1=[3,6,2,1]
(does not sort the list itself). print sorted(lst1)
O/P: [1, 2, 3, 6]
sum() Return the sum of all lst=[1,2,3,4,4,4]
elements in the list. print sum(lst)
O/P: 18

Python Programming (LJIET - 8-CE/IT Dept) 2018 15


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 Concatenation and repetition of List:


x=[1,2,3]
y=[4,5,6]
print x+y
print x*2

Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3]

 Tuples:
 Like strings, tuples are ordered sequences of elements. The difference is that the
elements of a tuple need not be characters. The individual elements can be of any
type, and need not be of the same type as each other.
 In Python programming, a tuple is similar to a list. The difference between the two is
that we cannot change the elements of a tuple once it is assigned whereas in a list,
elements can be changed.
 Advantages of Tuple over List:
Since, tuples are quite similiar to lists, both of them are used in similar situations as
well. However, there are certain advantages of implementing a tuple over a list.
Below listed are some of the main advantages:
1. We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
2. Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
3. Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
4. If you have data that doesn't change, implementing it as tuple will guarantee
that it remains write-protected.
 Literals of type tuple are written by enclosing a comma-separated list of elements
within parentheses.
 For example,
t1=()
t2=(1, 'two', 3)
t3=(1,) #singletone element
print (t1)
print (t2)
print (t3)

Python Programming (LJIET - 8-CE/IT Dept) 2018 16


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Output:
()
(1, 'two', 3)
(1,)

 Like strings, tuples can be concatenated, indexed, and sliced. Consider


t1 = (1, 'two', 3)
t2 = (t1, 3.25)
print (t2)
print (t1 + t2)
print ((t1 + t2)[3])
print ((t1 + t2)[2:5])

Output:
((1, 'two', 3), 3.25)
(1, 'two', 3, (1, 'two', 3), 3.25)
(1, 'two', 3)
(3, (1, 'two', 3), 3.25)

 Accessing tuple elements:


tup=(5,6,7,8,9)
print tup
print tup[:]
print tup[0]
print tup[4]
print tup[-1]
print tup[::2]

student =(10,'Alpa',20,30,40)
rno, name = student[0:2]
print rno
print name
marks=student[2:5]
for i in marks:
print i
Output:

 Basic Operation on tuple:


student =(10,'Alpa',20,30,40)
fees=(15000,)
print student+fees
print fees * 3

Python Programming (LJIET - 8-CE/IT Dept) 2018 17


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

print 'Alpa' in student


print 'Alpa' not in student

Output:

 Built-in Functions and method with Tuple:


Function Description Example
len() Return the length (the number tup1=(1,2,3,4)
of items) in the tuple. print len(tup1)
O/P: 4
max() Return the largest item in the tup1=(1,2,3,4)
tuple. print max(tup1)
O/P: 4
min() Return the smallest item in the tup1=(1,2,3,4)
tuple. print min(tup1)
O/P: 1
index() Returns the index of the first print tup1.index(4)
matched item O/P: 4
count() Returns the count of number of tup1=(1,2,3,4,4,4)
items passed as an argument print tup1.count(4)
O/P: 3
sorted() Return a new accending sorted tup1=(3,6,2,1)
tuple (does not sort the tuple print sorted(tup1)
itself),sorted(tup,reverse=True) print sorted(tup1,reverse=True)
will sort in reverse order. O/P: [1, 2, 3, 6]
[6, 3, 2, 1]

 Nested tuple:
emp=((90,'Alpa',30000),(52,'kinjal',25000),(64,'Bijal',35000))
print emp
print emp[1][1]
print sorted(emp)
print sorted(emp,reverse=True)
print sorted(emp,key=lambda x:x[1]) #sort on name
print sorted(emp,key=lambda x:x[2]) #sort on salary

Output:

Python Programming (LJIET - 8-CE/IT Dept) 2018 18


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 Tuples and Immutability:


Since tuples are immutable, we cannot modify the elements of the tuple once it is created.
Now, how to insert a new element into an existing tuple. Let‘s take ‗x‘ as an existing
tuple. Since ‗x‘ cannot be modified, we have to create a new tuple ‗y‘ with newly inserted
element.
 Inserting Element into a tuple at specific position:
The following logic can be used:
1. First of all, copy the elements of ‗x‘ from 0th poition to pos-2 position into ‗y‘
as: y=x [0 : pos-1 ]
2. Concatenate the new element to the new tuple ‗y‘. y = y + new
3. Concatenate the remaining elements (from pos-1 till end) of x to the new tuple
‗y‘. The total tuple can be stored again with the old name ‗x‘. x =y + x[pos – 1:]
num=(1,2,3,4)
print num
lst=[input('Enter a new number:')]
new=tuple(lst)
pos=input('Enter position no:')
num1=num[0:pos-1]
num1=num1+new
num=num1+num[pos-1:]
print num

Output:

 Modifying Element of a tuple at specific position:


The following logic can be used:
1. First of all, copy the elements of ‗x‘ from 0th poition to pos-2 position into ‗y‘
as: y=x [0 : pos-1 ]
2. Concatenate the new element to the new tuple ‗y‘. y = y + new
3. Concatenate the remaining elements (from pos-1 till end) of x to the new tuple
‗y‘. The total tuple can be stored again with the old name ‗x‘. x = y + x[pos:]
num=(1,2,3,4)
print num
lst=[input('Enter a new number:')]
new=tuple(lst)
pos=input('Enter position no:')
num1=num[0:pos-1]
num1=num1+new

Python Programming (LJIET - 8-CE/IT Dept) 2018 19


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

num=num1+num[pos:]
print num

Output:

 Deleting Element from a tuple at specific position:


The following logic can be used:
1. First of all, copy the elements of ‗x‘ from 0th poition to pos-2 position into ‗y‘
as: y=x [0 : pos-1 ]
2. Concatenate the remaining elements from ‗x‘ by eliminating the element which
is at ‗pos-1‘.It means we should concatenate elements from ‗pos‘ till the end.
The total tuple can be stored again with the old name ‗x‘. x = y + x[pos:]
num=(1,2,3,4)
print num
pos=input('Enter position no:')
num1=num[0:pos-1]
num=num1+num[pos:]
print num

Output:

 Dictionary:
Objects of type dict (short for dictionary) are like lists except that ―indices‖ need not be
integers—they can be values of any immutable type. Since they are not ordered, we call
them keys rather than indices. Think of a dictionary as a set of key/value pairs. Literals of
type dict are enclosed in curly braces, and each element is written as a key followed by a
colon followed by a value.
Example:
monthNumbers = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4,
'May':5,1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May'}
print ('The third month is ' + monthNumbers[3])
dist = monthNumbers['Apr'] - monthNumbers['Jan']
print ('Apr and Jan are', dist, 'months apart')

Python Programming (LJIET - 8-CE/IT Dept) 2018 20


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Output:
The third month is Mar
Apr and Jan are 3 months apart

Example:
#Different type Dict creating
my_dict = {}
my_dict = {1: 'apple', 2: 'ball'}
my_dict = {'name': 'John', 1: [2, 4, 3]}
my_dict = dict({1:'apple', 2:'ball'})
my_dict = dict([(1,'apple'), (2,'ball')])
my_dict = {'name':'Jack', 'age': 26}
print("Displying Dictionary")
print(my_dict)
print(my_dict['name'])
print(my_dict.get('age'))
print("change element of Dictionary")
my_dict['age'] = 27
print(my_dict)
print("add element to Dictionary")
my_dict['address'] = 'Downtown'
print(my_dict)
print("delete element from Dictionary")
del my_dict['address']
print(my_dict)
print(my_dict.popitem())
print("fromkey method")
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
list(sorted(marks.keys()))

Output:
Displying Dictionary
{'name': 'Jack', 'age': 26}
Jack
26
change element of Dictionary
{'name': 'Jack', 'age': 27}
add element to Dictionary
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
delete element from Dictionary
{'name': 'Jack', 'age': 27}
('age', 27)
fromkey method
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)

Python Programming (LJIET - 8-CE/IT Dept) 2018 21


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 Python Dictionary Methods:


Methods Description Example
Remove all items form the d={1:'alpa',2:'kinjal'}
dictionary. d.clear()
clear()
print d
O/P: {}
copy() Return a shallow copy of the d={1:'alpa',2:'kinjal'}
dictionary. d1=d.copy()
print d, d1
O/P: {1: 'alpa', 2: 'kinjal'} {1: 'alpa',
2: 'kinjal'}
fromkeys(seq[, v]) Return a new dictionary Print {}.fromkeys([1,2,3],'same')
with keys from seq and O/P: {1: 'same', 2: 'same', 3: 'same'}
value equal to v(defaults
to None).
get(key[,d]) Return the value of key. d={1:'alpa',2:'kinjal'}
If key does not exit, print d.get(1,'none'), d.get(3,'none')
return d (defaults to None). O/P: alpa none
items() Return a new view of the d={1:'alpa',2:'kinjal'}
dictionary's items (key, print d.items()
value). O/P: [(1, 'alpa'), (2, 'kinjal')]
keys() Return a new view of the d={1:'alpa',2:'kinjal'}
dictionary's keys. print d.keys()
O/P: [1, 2]

pop(key[,d]) Remove the item d={1:'alpa',2:'kinjal'}


with key and return its value print d.pop(1,'Not Present')
or d if key is not found. print d.pop(3,'Not Present')
If d is not provided O/P:
and key is not found, alpa
raises KeyError Not Present

popitem() Remove and return an d={1:'alpa',2:'kinjal'}


arbitary item (key, value). print d.popitem()
Raises KeyError if the O/P:
dictionary is empty. (2, 'kinjal')
setdefault(key[,d]) If key is in the dictionary, d={1:'alpa',2:'kinjal'}
return its value. If not, print d.setdefault(2,0)
insert key with a value print d.setdefault(3,'varsha')
of d and return d (defaults print d
to None). O/P:
kinjal
varsha
{1: 'alpa', 2: 'kinjal', 3: 'varsha'}
update([other]) Update the dictionary with d={1:'alpa',2:'kinjal',3:'varsha'}
the key/value pairs ud={3:'shefa'}
from other, overwriting d.update(ud)
existing keys. print d
ud={4:'varsha'}

Python Programming (LJIET - 8-CE/IT Dept) 2018 22


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

d.update(ud)
print d
O/P: {1: 'alpa', 2: 'kinjal', 3: 'shefa'}
{1:'alpa',2: 'kinjal',3: 'shefa',4: 'varsha'}
values() Return a new view of the d={1:'alpa',2:'kinjal',3:'varsha'}
dictionary's values print d.values()
O/P: ['alpa', 'kinjal', 'shefa']

 Built-in Functions with Dictionary:


Functions Description Example
Return True if all keys of d={1:'alpa',2:'kinjal',3:'varsha'}
all() the dictionary are true (or if print all(d)
the dictionary is empty). O/P: True
any() Return True if any key of the d={1:'alpa',2:'kinjal',3:'varsha'}
dictionary is true. If the print any(d)
dictionary is empty, O/P: True
return False.
len() Return the length (the d={1:'alpa',2:'kinjal',3:'varsha'}
number of items) in the print len(d)
dictionary. O/P: 3
cmp() Compares items of two d1={1:10,2:20}
dictionaries. d2={1:10,2:20}
print cmp(d1,d2)
d2={1:10,2:30}
print cmp(d1,d2)
d2={1:10,2:20,3:30}
print cmp(d1,d2)
d1={1:10,2:20,3:30,4:40}
print cmp(d1,d2)
O/P:
0
-1
-1
1
sorted() Return a new sorted list of Shown in sorting of dictonary
keys in the dictionary.

 Dictionary comprehension is an elegant and concise way to create new dictionary


from an iterable in Python. Dictionary comprehension consists of an expression pair
(key: value) followed by forstatement inside braces {}.curly

squares = {x: x*x for x in range(6)}


print(squares)

#equivalent to this code


squares1 = {}
for x in range(6):

Python Programming (LJIET - 8-CE/IT Dept) 2018 23


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

squares1[x] = x*x
print(squares1)

odd_squares = {x: x*x for x in range(11) if x%2 == 1}


print(odd_squares)

Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

 Dictionary Membership Test:


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 in squares)
print(49 in squares)

Output:
True
False
False

 Iterating Through a Dictionary


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

Output:
1
9
25
49
81

 Sorting Elements of a Dictionary using lambdas:


colors={10:'red',35:'green',15:'blue',25:'white'}

#sorting of list by key in ascending order


c1=sorted(colors.items(), key=lambda x:x[0])
print c1

#sorting of list by value in ascending order


c2=sorted(colors.items(), key=lambda x:x[1])
print c2

#sorting of list by key in descending order


c3=sorted(colors.items(), reverse=True, key=lambda x:x[0])
print c3

#sorting of list by value in descending order


c4=sorted(colors.items(), reverse=True, key=lambda x:x[1])
print c4

Python Programming (LJIET - 8-CE/IT Dept) 2018 24


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Output:
[(10, 'red'), (15, 'blue'), (25, 'white'), (35, 'green')]
[(15, 'blue'), (35, 'green'), (10, 'red'), (25, 'white')]
[(35, 'green'), (25, 'white'), (15, 'blue'), (10, 'red')]
[(25, 'white'), (10, 'red'), (35, 'green'), (15, 'blue')]

 Converting list into Dictionary:


countries=['USA','INDIA','GERMANY']
cities=['WASHINGTON','NEW DELHI','BERLIN']

#to make dictionary using zip() function


z=zip(countries,cities)
d=dict(z)
print d

Output:
{'GERMANY': 'BERLIN', 'INDIA': 'NEW DELHI', 'USA': 'WASHINGTON'}

 Converting strings into Dictionary:


str1="Alpa=10,Varsha=20,Shefa=30"
lst=[]
for x in str1.split(','):
y=x.split('=')
lst.append(y)
d=dict(lst)
print d

Output:
{'Shefa': '30', 'Alpa': '10', 'Varsha': '20'}

 Ordered Dictionary:
An ordered dictionary is a dictionary but it will keep the order of the elements. The
elements are stored and maintained in the same order as they were entered into the
ordered dictionary.
from collections import OrderedDict
d=OrderedDict()
d[10]='A'
d[11]='B'
d[12]='C'

for i,j in d.items():


print i, j

Output:
10 A
11 B
12 C

Python Programming (LJIET - 8-CE/IT Dept) 2018 25


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 Lists and Mutability :


 The empty list is written as [], and singleton lists are written without that (oh so easy to
forget) comma before the closing bracket.
L = ['I did it all', 4, 'Money']
for i in range(len(L)):
print (L[i])
Output:
I did it all
4
Money

Lists differ from tuples in one hugely important way: lists are mutable. In contrast,
tuples and strings are immutable. There are many operators that can be used to create
objects of these immutable types, and variables can be bound to objects of these types.
But objects of immutable types cannot be modified. On the other hand, objects of type
list can be modified after they are created.

 Cloning:
Though allowed, it is usually prudent to avoid mutating a list over which one is
iterating.
def removeDups(L1, L2):
"""Assumes that L1 and L2 are lists.
Removes any element from L1 that also occurs in L2"""
for e1 in L1:
if e1 in L2:
L1.remove(e1)
L1 = [1,2,3,4]
L2 = [1,2,5,6]
removeDups(L1, L2)
print ('L1 =', L1)

Output:
L1 = [2, 3, 4]

 List Comprehension:
List comprehension provides a concise way to apply an operation to the values in a
sequence. It creates a new list in which each element is the result of applying a given
operation to a value from a sequence (e.g., the elements in another list).
L = [x**2 for x in range(1,7)]
print (L)

Output:
[1, 4, 9, 16, 25, 36]

Python Programming (LJIET - 8-CE/IT Dept) 2018 26


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

The for clause in a list comprehension can be followed by one or more if and for
statements that are applied to the values produced by the for clause. These additional
clauses modify the sequence of values generated by the first for clause and produce a
new sequence of values, to which the operation associated with the comprehension is
applied.
mixed = [1, 2, 'a', 3, 4.0]
print ([x**2 for x in mixed if type(x) == int])

Output:
[1, 4, 9]

 Function as objects :
 In Python, functions are first-class objects. That means that they can be treated like
objects of any other type, e.g., int or list. They have types, e.g., the expression type(fact)
has the value <type 'function'>; they can appear in expressions, e.g., as the right-hand side
of an assignment statement or as an argument to a function; they can be elements of lists;
etc.
 Using functions as arguments can be particularly convenient in conjunction with lists. It
allows a style of coding called higher-order programming.
def factI(n):
"""Assumes that n is an int > 0
Returns n!"""
result = 1
while n > 1:
result = result * n
n -= 1
return result
def factR(n):
"""Assumes that n is an int > 0
Returns n!"""
if n == 1:
return n
else:
return n*factR(n - 1)

def fib(n):
"""Assumes n an int >= 0
Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def testFib(n):
for i in range(n+1):
print 'fib of', i, '=', fib(i)

def applyToEach(L, f):

Python Programming (LJIET - 8-CE/IT Dept) 2018 27


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

"""Assumes L is a list, f a function


Mutates L by replacing each element, e, of L by f(e)"""
for i in range(len(L)):
L[i] = f(L[i])
L = [1, -2, 3.33]
print 'L =', L
print 'Apply abs to each element of L.'
applyToEach(L, abs)
print 'L =', L
print 'Apply int to each element of', L
applyToEach(L, int)
print 'L =', L
print 'Apply factorial to each element of', L
applyToEach(L, factR)
print 'L =', L
print 'Apply Fibonnaci to each element of', L
applyToEach(L, fib)
print 'L =', L

Output:
L = [1, -2, 3.33]
Apply abs to each element of L.
L = [1, 2, 3.33]
Apply int to each element of [1, 2, 3.33]
L = [1, 2, 3]
Apply factorial to each element of [1, 2, 3]
L = [1, 2, 6]
Apply Fibonnaci to each element of [1, 2, 6]
L = [1, 2, 13]

 Python has a built-in higher-order function, map, that is similar to, but more general
than, the applyToEach function defined.
 In its simplest form the first argument to map is a unary function (i.e., a function that
has only one parameter) and the second argument is any ordered collection of values
suitable as arguments to the first argument.
 It returns a list generated by applying the first argument to each element of the second
argument.
 For example, the expression map(fact, [1, 2, 3]) has the value [1, 2, 6]. More
generally, the first argument to map can be of function of n arguments, in which case
it must be followed by n subsequent ordered collections.
L1 = [100, -28, 36]
L2 = [2, 57, 9]
print map(abs,L1)
print map(min, L1, L2)

Output:
[100, 28, 36]
[2, -28, 9]

Python Programming (LJIET - 8-CE/IT Dept) 2018 28


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

 The lambda operator or lambda function is a way to create small anonymous


functions, i.e. functions without a name. These functions are throw-away functions,
i.e. they are just needed where they have been created. Lambda functions are mainly
used in combination with the functions filter(), map() and reduce().
 filter(), map() and reduce() are inbuilt functions which are examples of function as a
parameter.
 Function as parameter: The map() Function:
r = map(func, seq)

The first argument func is the name of a function and the second a sequence (e.g. a
list) seq. map() applies the function func to all the elements of the sequence seq. It
returns a new list with the elements changed by func.
Example-1 Of map():
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)

F = map(fahrenheit, temp)
C = map(celsius, F)

Output:
>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
>>> print Fahrenheit
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]
>>> C = map(lambda x: (float(5)/9)*(x-32), Fahrenheit)
>>> print C
[39.200000000000003, 36.5, 37.300000000000004, 37.799999999999997]

Example-2 Of map() using lambda function as parameter:


>>> a = [1,2,3,4]
>>> b = [17,12,11,10]
>>> c = [-1,-4,5,9]
>>> map(lambda x,y:x+y, a,b)
[18, 14, 14, 14]
>>> map(lambda x,y,z:x+y+z, a,b,c)
[17, 10, 19, 23]
>>> map(lambda x,y,z:x+y-z, a,b,c)
[19, 18, 9, 5]
 Function as parameter: The filter() Function:
r = filter(function, list)
The function filter(function, list) offers an elegant way to filter out all the elements of
a list, for which the function function returns True.

Python Programming (LJIET - 8-CE/IT Dept) 2018 29


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

The function filter(f,l) needs a function f as its first argument. f returns a Boolean
value, i.e. either True or False. This function will be applied to every element of the
list l. Only if f returns True will the element of the list be included in the result list.

>>> fib = [0,1,1,2,3,5,8,13,21,34,55]


>>> result = filter(lambda x: x % 2, fib)
>>> print result
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result
[0, 2, 8, 34]
>>>
 Function as parameter: The reduce () Function:
r = reduce(function, list)
The function reduce(func, seq) continually applies the function func() to the sequence seq. It
returns a single value.

If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq) works like this:

 At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on
which reduce() works looks now like this: [ func(s1, s2), s3, ... , sn ]
 In the next step func will be applied on the previous result and the third element of the
list, i.e. func(func(s1, s2),s3)
The list looks like this now: [ func(func(s1, s2),s3), ... , sn ]
 Continue like this until just one element is left and return this element as the result of
reduce()

We illustrate this process in the following example:


>>> reduce(lambda x,y: x+y, [47,11,42,13])
113
The following diagram shows the intermediate steps of the calculation:

Examples of reduce():
1) Determining the maximum of a list of numerical values by using reduce:

>>> f = lambda a,b: a if (a > b) else b


>>> reduce(f, [47,11,42,102,13])
102
>>>
2) Calculating the sum of the numbers from 1 to 100:

>>> reduce(lambda x, y: x+y, range(1,101))


5050

Python Programming (LJIET - 8-CE/IT Dept) 2018 30


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Python Built-in Function: (May ask in unit-2)


The Python interpreter has a number of functions that are always available for use. These
functions are called built-in functions. For example, print() function prints the given object to
the standard output device (screen) or to the text stream file.
(Note: bold function names are already covered in previous examples, Write no of functions as per
marks asked in exam)

Method Description
abs() returns absolute value of a number
all() returns true when all elements in iterable is true
any() Checks if any Element of an Iterable is True
ascii() Returns String Containing Printable Representation
bin() converts integer to binary string
bool() Coverts a Value to Boolean
bytearray() returns array of given byte size
bytes() returns immutable bytes object
callable() Checks if the Object is Callable
chr() Returns a Character (a string) from an Integer
classmethod() returns class method for given function
compile() Returns a Python code object
complex() Creates a Complex Number
delattr() Deletes Attribute From the Object
dict() Creates a Dictionary
dir() Tries to Return Attributes of Object
divmod() Returns a Tuple of Quotient and Remainder
enumerate() Returns an Enumerate Object
eval() Runs Python Code Within Program
exec() Executes Dynamically Created Program
filter() constructs iterator from elements which are true
float() returns floating point number from number, string
format() returns formatted representation of a value
frozenset() returns immutable frozenset object
getattr() returns value of named attribute of an object
globals() returns dictionary of current global symbol table
hasattr() returns whether object has named attribute
hash() returns hash value of an object

Python Programming (LJIET - 8-CE/IT Dept) 2018 31


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Method Description
help() Invokes the built-in Help System
hex() Converts to Integer to Hexadecimal
id() Returns Identify of an Object
input() reads and returns a line of string
int() returns integer from a number or string
isinstance() Checks if a Object is an Instance of Class
issubclass() Checks if a Object is Subclass of a Class
iter() returns iterator for an object
len() Returns Length of an Object
list() Function creates list in Python
locals() returns dictionary of current local symbol table
map() Applies Function and Returns a List
max() returns largest element
memoryview() returns memory view of an argument
min() returns smallest element
next() Retrieves Next Element from Iterator
object() Creates a Featureless Object
oct() converts integer to octal
open() Returns a File object
ord() returns Unicode code point for Unicode character
pow() returns x to the power of y
print() Prints the Given Object
property() returns a property attribute
range() return sequence of integers between start and stop
repr() returns printable representation of an object
reversed() returns reversed iterator of a sequence
round() rounds a floating point number to ndigits places.
set() returns a Python set
setattr() sets value of an attribute of object
slice() creates a slice object specified by range()
sorted() returns sorted list from a given iterable
staticmethod() creates static method from a function
str() returns informal representation of an object
sum() Add items of an Iterable

Python Programming (LJIET - 8-CE/IT Dept) 2018 32


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

Method Description
super() Allow you to Refer Parent Class by super
tuple() Function Creates a Tuple
type() Returns Type of an Object
vars() Returns __dict__ attribute of a class
zip() Returns an Iterator of Tuples
__import__() Advanced Function Called by import

Q: Write a program to open the file test.txt and read it line by line. For each line, split
the line into a list of words using the split function. For each word, check to see if the
word is already in a list. If the word is not in the list, add it to the list. When the
program completes, sort and print the resulting words in alphabetical order.
File: test.txt
hello this is an apple
apple is fruit

File:FileWordListSort.py
# File words list and sort it
fname = ' test.txt'
wordlist = []
with open(fname, 'r') as f:
for line in f:
words = line.split()
for word in words:
if word not in wordlist:
wordlist.append(word)

# sort the list


wordlist.sort()

# display the sorted words


print("The sorted words are:")
for word in wordlist:
print(word)

Output:

Q: Write a program that reads the words in words.txt and stores them as keys in a
dictionary and count the frequency of it as a value and print 10 records with highest.

Python Programming (LJIET - 8-CE/IT Dept) 2018 33


L.J. Institute of Engineering & Technology Semester: VIII (2018) PP (2180711)

File: wordcount.py
#wordcount program
fr = open("1.txt")
wc = {}
wl=[]
for line in fr:
words = line.split()
for word in words:
word=word.lower()
if word not in wc:
wc[word] = 1
else:
wc[word] += 1

for k,v in wc.items():


wl.append((v,k))

wl.sort(reverse=True)
#print wl
#print "Sort dic : ",wc
i = 0
for key in wc:
i+=1
print key, " - ", wc[key]
if i==10:
break

Output:

Q: Give the output of following Python code [Nov-2017][LJIET]:


l=[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print l

Output:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Q: Give the output of following Python code [Nov-2017][LJIET]:


str1 = ‘This is Pyhton’
print "Slice of String : ", str1[1 : 4 : 1]
print "Slice of String : ", str1[0 : -1 : 2]

Output:
Slice of String : his
Slice of String : Ti sPho

Python Programming (LJIET - 8-CE/IT Dept) 2018 34

You might also like