0% found this document useful (0 votes)
6 views49 pages

Unit 4 and 5 - Python BISM

The document provides a comprehensive overview of strings and lists in Python, detailing their properties, operations, and built-in functions. It explains string immutability, indexing, slicing, and various operators, along with examples of string manipulation and comparison. Additionally, it introduces lists, highlighting their mutable nature, creation methods, and differences from strings.

Uploaded by

priyankavelu0403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views49 pages

Unit 4 and 5 - Python BISM

The document provides a comprehensive overview of strings and lists in Python, detailing their properties, operations, and built-in functions. It explains string immutability, indexing, slicing, and various operators, along with examples of string manipulation and comparison. Additionally, it introduces lists, highlighting their mutable nature, creation methods, and differences from strings.

Uploaded by

priyankavelu0403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

STRING IN PYTHON

6.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
➢ Strings are immutable in python. It means it is unchangeable. At the same memory
address, the new value cannot be stored.

➢ Each character has its index or can be accessed using its index.

➢ String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3, ........... in the backward direction.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1

➢ The index of string in forward direction starts from 0 and in backward direction starts from
-1.
➢ The size of string is total number of characters present in the string. (If there are n
characters in the string, then last index in forward direction would be n-1 and last index in
backward direction would be –n.)

➢ String are stored each character in contiguous location.


➢ The character assignment is not supported in string because strings are immutable.
Example :
str = “kendriya”
str[2] = ‘y’ # it is invalid. Individual letter assignment not allowed in python

6.2 Traversing a String:


Access the elements of string, one character at a time.
str = “kendriya”
for ch in str :
print(ch, end= ‘ ‘)
Output:
kendriya

6.3 String Operators:


a. Basic Operators (+, *)
b. Membership Operators ( in, not in)
c. Comparison Operators (==, !=, <, <=, >, >=)

a. Basic Operators: There are two basic operators of strings:


i. String concatenation Operator (+)
ii. String repetition Operator (*)

i. String concatenation Operator: The + operator creates a new string by joining the two
operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’

Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
ii. String repetition Operator: It is also known as String replication operator. It requires
two types of operands- a string and an integer number.
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’

Note:You cannot have strings as n=both the operands with * operator.


Example:
>>>”you” * “you” # can't multiply sequence by non-int of type 'str'
It is invalid and generates an error.

b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise False
not in - Returns True if a character or a substring does not exist in the given string; otherwise False

Example:
>>> "ken" in "Kendriya Vidyalaya"
False
>>> "Ken" in "Kendriya Vidyalaya"
True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False

c. Comparison Operators: These operators compare two strings character by character


according to their ASCII value.
Characters ASCII (Ordinal) Value

‘0’ to ‘9’ 48 to 57

‘A’ to ‘Z’ 65 to 90

‘a’ to ‘z’ 97 to 122

Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True

6.4 Finding the Ordinal or Unicode value of a character:


Function Description
ord(<character>) Returns ordinal value of a character

chr(<value>) Returns the corresponding character

Example:
>>> ord('b')
98
>>> chr(65)
'A'
Program: Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")

print("Do you want to continue? Y/N")


option=input()
if option=='y' or option=='Y':
var=True
else:
var=False

6.5 Slice operator with Strings:


The slice operator slices a string using a range of indices.
Syntax:
string-name[start:end]
where start and end are integer indices. It returns a string from the index start to end-1.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
d a t a s t r u c t u r e
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
>>> str="data structure"
>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0.
'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string)
'data structure'
>>> str[7:]
'ructure'
>>> str[4:]+str[:4]
' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string
'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a string
'erutcurts atad'

Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the
index does not cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
' ' # returns empty string
>>> str[10:16]
'ture'

Reason: When you use an index, you are accessing a particular character of a string, thus the
index must be valid and out of bounds index causes an error as there is no character to return
from the given index.
But slicing always returns a substring or empty string, which is valid sequence.

6.6 Built-in functions of string:


Example:
str=”data structure”
s1= “hello365”
s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’
S. No. Function Description Example
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its first character >>> str.capitalize()
capitalized. 'Data structure'
3 find(sub,start,end) Returns the lowest index in the string where the >>> str.find("ruct",5,13)
substring sub is found within the slice range. 7
Returns -1 if sub is not found. >>> str.find("ruct",8,13)
-1
4 isalnum( ) Returns True if the characters in the string are >>>s1.isalnum( )
alphabets or numbers. False otherwise True
>>>s2.isalnum( )
True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
5 isalpha( ) Returns True if all characters in the string are >>>s1.isalpha( )
alphabetic. False otherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
6 isdigit( ) Returns True if all the characters in the string are >>>s1.isdigit( )
digits. False otherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower( ) Returns True if all the characters in the string are >>> s1.islower()
lowercase. False otherwise. True
>>> s2.islower()
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True
8 isupper( ) Returns True if all the characters in the string are >>> s1.isupper()
uppercase. False otherwise. False
>>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
9 isspace( ) Returns True if there are only whitespace >>> " ".isspace()
characters in the string. False otherwise. True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase characters. >>> "HeLlo".lower()
'hello'
11 upper( ) Converts a string in uppercase characters. >>> "hello".upper()
'HELLO'
12 lstrip( ) Returns a string after removing the leading >>> str="data structure"
characters. (Left side). >>> str.lstrip('dat')
if used without any argument, it removes the ' structure'
leading whitespaces. >>> str.lstrip('data')
' structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after removing the trailing >>> str.rstrip('eur')
characters. (Right side). 'data struct'
if used without any argument, it removes the >>> str.rstrip('rut')
trailing whitespaces. 'data structure'
>>> str.rstrip('tucers')
'data '
14 split( ) breaks a string into words and creates a list out of it >>> str="Data Structure"
>>> str.split( )
['Data', 'Structure']
Programs related to Strings:
1. Write a program that takes a string with multiple words and then capitalize the first
letter of each word and forms a new string out of it.
Solution:
s1=input("Enter a string : ")
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)

2. Write a program that reads a string and checks whether it is a palindrome string or
not.
str=input("Enter a string : ")
n=len(str)
mid=n//2
rev=-1
for i in range(mid):
if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
else:
print("String is palindrome")

3. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=str.lower()
print(s1)
elif choice==2:
s1=str.upper()
print(s1)
else:
print("Invalid choice entered")
LIST IN PYTHON

Introduction:

▪ List is a collection of elements which is ordered and changeable (mutable).


▪ Allows duplicate values.
▪ A list contains items separated by commas and enclosed within square brackets ([ ]).
▪ All items belonging to a list can be of different data type.
▪ The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list.

Difference between list and string:

List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:

>>>L=[7,4,8,9] >>>str= “python”

>>>L[2]=6 #valid >>>str[2]= ‘p’ #error

7.2 Creating a list:

To create a list enclose the elements of the list within square brackets and separate the
elements by commas.

Syntax:

list-name= [item-1, item-2, .......... , item-n]

Example:

mylist = ["apple", "banana", "cherry"] # a list with three items

L=[] # an empty list

7.2.1 Creating a list using list( ) Constructor:

o It is also possible to use the list( ) constructor to make a list.


mylist = list(("apple", "banana", "cherry")) #note the double round-brackets
print(mylist)

L=list( ) # creating empty list

7.2.2 Nested Lists:

>>> L=[23,'w',78.2, [2,4,7],[8,16]]

>>> L

[23, 'w', 78.2, [2, 4, 7], [8, 16]]

7.2.3 Creating a list by taking input from the user:

>>> List=list(input("enter the elements: "))

enter the elements: hello python

>>> List

['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']

>>> L1=list(input("enter the elements: "))

enter the elements: 678546

>>> L1

['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits

To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.

>>> L1=eval(input("enter the elements: "))

enter the elements: 654786

>>> L1

654786 # it is an integer, not a list

>>> L2=eval(input("enter the elements: "))


enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket

>>> L2

[6, 7, 8, 5, 4, 3]

Note: With eval( ) method, If you enter elements without square bracket[ ], it will be
considered as a tuple.

>>> L1=eval(input("enter the elements: "))

enter the elements: 7,65,89,6,3,4

>>> L1

(7, 65, 89, 6, 3, 4) #tuple

7.3 Accessing lists:

➢ The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes.
➢ List-name[start:end] will give you elements between indices start to end-1.
➢ The first item in the list has the index zero (0).

Example:
>>> number=[12,56,87,45,23,97,56,27]

Forward Index
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
Backward Index

>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]

7.4 Traversing a LIST:

Traversing means accessing and processing each element.

Method-1:

>>> day=list(input("Enter elements :"))


Enter elements : sunday
>>> for d in day:
print(d)

Output:
s
u
n
d
a
y

Method-2
>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])

Output:
w
e
d
n
e
s
d
a
y

7.5 List Operators:

➢ Joining operator +
➢ Repetition operator *
➢ Slice operator [:]
➢ Comparison Operator <, <=, >, >=, ==, !=
• Joining Operator: It joins two or more lists.

Example:

>>> L1=['a',56,7.8]

>>> L2=['b','&',6]

>>> L3=[67,'f','p']

>>> L1+L2+L3

['a', 56, 7.8, 'b', '&', 6, 67, 'f', 'p']

• Repetition Operator: It replicates a list specified number of times.

Example:

>>> L1*3

['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]

>>> 3*L1

['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]

• Slice Operator:

List-name[start:end] will give you elements between indices start to end-1.

>>> number=[12,56,87,45,23,97,56,27]

>>> number[2:-2]

[87, 45, 23, 97]

>>> number[4:20]

[23, 97, 56, 27]

>>> number[-1:-6]

[]

>>> number[-6:-1]

[87, 45, 23, 97, 56]


>>> number[0:len(number)]

[12, 56, 87, 45, 23, 97, 56, 27]

List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.

>>> number[1:6:2]

[56, 45, 97]

>>> number[: : -1]

[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list

List modification using slice operator:

>>> number=[12,56,87,45,23,97,56,27]

>>> number[2:4]=["hello","python"]

>>> number

[12, 56, 'hello', 'python', 23, 97, 56, 27]

>>> number[2:4]=["computer"]

>>> number

[12, 56, 'computer', 23, 97, 56, 27]

Note: The values being assigned must be a sequence (list, tuple or string)

Example:

>>> number=[12,56,87,45,23,97,56,27]

>>> number=[12,56,87,45,23,97,56,27]

>>> number[2:3]=78 # 78 is a number, not a sequence

TypeError: can only assign an iterable


• Comparison Operators:

o Compares two lists


o Python internally compares individual elements of lists in lexicographical order.
o It compares the each corresponding element must compare equal and two
sequences must be of the same type.
o For non-equal comparison as soon as it gets a result in terms of True/False,
from corresponding elements’ comparison. If Corresponding elements are equal,
it goes to the next element and so on, until it finds elements that differ.

Example:

>>>L1, L2 = [7, 6, 9], [7, 6, 9]

>>>L3 = [7, [6, 9] ]

For Equal Comparison:

Comparison Result Reason


>>>L1==L2 True Corresponding elements have same value and same
type
>>>L1==L3 False Corresponding values are not same

For Non-equal comparison:

Comparison Result Reason


>>> L1>L2 False All elements are equal
>>> L2>L3 TypeError: '>' not in L2, element at the index 1 is int type
supported between and in L3 element at the index 1 is list
instances of 'int' and
type
'list'
>>>[3,4,7,8]<[5,1] True 3<5 is True
>>>[3,4,7,8]<[3,4,9,2] True First two elements are same so move
to next element and 7<9 is True

>>>[3,4,7,8]<[3,4,9,11] True 7<9 is True


>>>[3,4,7,8]<[3,4,7,5] False 8<5 is False
List Methods:

Consider a list:

company=["IBM","HCL","Wipro"]

S. Function
No.
Description Example
Name
1 append( ) To add element to the list >>> company.append("Google")
at the end. >>> company
Syntax: ['IBM', 'HCL', 'Wipro', 'Google']
list-name.append (element)
Error:
>>>company.append("infosys","microsoft") # takes exactly one element
TypeError: append() takes exactly one argument (2 given)

2 extend( ) Add a list, to the end of >>>company=["IBM","HCL","Wipro"]


the current list. >>> desktop=["dell","HP"]
Syntax: >>> company.extend(desktop)
list-name.extend(list) >>> company
['IBM', 'HCL', 'Wipro', 'dell', 'HP']
Error:
>>>company.extend("dell","HP") #takes only a list as argument
TypeError: extend() takes exactly one argument (2 given)

3. len( ) Find the length of the list. >>>company=["IBM","HCL","Wipro"]


Syntax: >>> len(company)
len(list-name) 3
>>> L=[3,6,[5,4]]
>>> len(L)
3

4 index( ) Returns the index of the >>> company = ["IBM", "HCL", "Wipro",
first element with the "HCL","Wipro"]
specified value. >>> company.index("Wipro")
Syntax: 2
list-name.index(element)
Error:
>>> company.index("WIPRO") # Python is case-sensitive language
ValueError: 'WIPRO' is not in list
>>> company.index(2) # Write the element, not index
ValueError: 2 is not in list
5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro"]
specified position. >>> company.insert(2,"Apple")
>>> company
Syntax: ['IBM', 'HCL', 'Apple', 'Wipro']
list.insert(index, element)
>>> company.insert(16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']

>>> company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']

6 count( ) Return the number of >>> company = ["IBM", "HCL",


times the value appears. "Wipro", "HCL","Wipro"]
Syntax: >>> company.count("HCL")
list-name.count(element) 2
>>> company.count("TCS")
0

7 remove( ) To remove an element >>> company = ["IBM", "HCL",


from the list. "Wipro", "HCL","Wipro"]
Syntax: >>> company.remove("Wipro")
list-name.remove(element) >>> company
['IBM', 'HCL', 'HCL', 'Wipro']
Error:
>>> company.remove("Yahoo")
ValueError: list.remove(x): x not in list
8 clear( ) Removes all the elements >>> company=["IBM","HCL", "Wipro"]
from list.
Syntax: >>> company.clear( )
list-name.clear( )
>>> company

[]
9 pop( ) Removes the element at >>>company=["IBM","HCL", "Wipro"]
the specified position and >>> company.pop(1)
returns the deleted 'HCL'
element. >>> company
Syntax: ['IBM', 'Wipro']
list-name.pop(index)
>>> company.pop( )
The index argument is
'Wipro'
optional. If no index is
specified, pop( ) removes and
returns the last item in the list.

Error:
>>>L=[ ]
>>>L.pop( )
IndexError: pop from empty list
10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]
>>> L=company.copy( )
Syntax: >>> L
list-name.copy( ) ['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the >>>company=["IBM","HCL", "Wipro"]
list. >>> company.reverse()
Syntax: >>> company
list-name.reverse( ) ['Wipro', 'HCL', 'IBM']

Takes no argument,
returns no list.
12. sort( ) Sorts the list. By default >>>company=["IBM","HCL", "Wipro"]
in ascending order. >>>company.sort( )
>>> company
Syntax: ['HCL', 'IBM', 'Wipro']
list-name.sort( )
To sort a list in descending order:

>>>company=["IBM","HCL", "Wipro"]
>>> company.sort(reverse=True)
>>> company
['Wipro', 'IBM', 'HCL']
Deleting the elements from the list using del statement:

Syntax:

del list-name[index] # to remove element at specified index

del list-name[start:end] # to remove elements in list slice

Example:

>>> L=[10,20,30,40,50]

>>> del L[2] # delete the element at the index 2

>>> L

[10, 20, 40, 50]

>>> L= [10,20,30,40,50]

>>> del L[1:3] # deletes elements of list from index 1 to 2.

>>> L

[10, 40, 50]

>>> del L # deletes all elements and the list object too.

>>> L

NameError: name 'L' is not defined


Difference between del, remove( ), pop( ), clear( ):

S.
del remove( ) pop( ) clear( )
No.

1 Statement Function Function Function

Deletes a single element Removes the first Removes an


Removes all the
2 or a list slice or complete matching item individual item and
elements from list.
list. from the list. returns it.
Removes all elements Removes all
3 and deletes list object elements but list
too. object still exists.

Difference between append( ), extend( ) and insert( ) :

S.
append( ) extend( ) insert( )
No.
Adds an element at the
Adds single element in the end Add a list in the end of specified position.
1
of the list. the another list
(Anywhere in the list)
Takes one list as Takes two arguments,
2 Takes one element as argument
argument position and element.
The length of the list
The length of the list will The length of the list
3 will increase by the
increase by 1. will increase by 1.
length of inserted list.

ACCESSING ELEMENTS OF NESTED LISTS:


Example:
>>> L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"]
>>> L[0][0]
'P'
>>> L[3][0][2]
'd'
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range

Programs related to lists in python:


Program-1 Write a program to find the minimum and maximum number in a list.

L=eval(input("Enter the elements: "))


n=len(L)
min=L[0]
max=L[0]
for i in range(n):
if min>L[i]:
min=L[i]
if max<L[i]:
max=L[i]

print("The minimum number in the list is : ", min)


print("The maximum number in the list is : ", max)
Program-2 Find the second largest number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
max=second=L[0]
for i in range(n):
if max<L[i]>second:
max=L[i]
seond=max

print("The second largest number in the list is : ", second)

Program-3: Program to search an element in a list. (Linear Search).

L=eval(input("Enter the elements: "))


n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")

Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
CHAPTER-8
TUPLE IN PYTHON

8.1 INTRODUCTION:

▪ Tuple is a collection of elements which is ordered and unchangeable (Immutable).


Immutable means you cannot change elements of a tuple in place.
▪ Allows duplicate members.
▪ Consists the values of any type, separated by comma.
▪ Tuples are enclosed within parentheses ( ).
▪ Cannot remove the element from a tuple.

8.2 Creating Tuple:

Syntax:

tuple-name = ( ) # empty tuple

tuple-name = (value-1, value-2, ........... , value-n)

Example:

>>> T=(23, 7.8, 64.6, 'h', 'say')

>>> T

(23, 7.8, 64.6, 'h', 'say')

8.2.1 Creating a tuple with single element:

>>> T=(3) #With a single element without comma, it is a value only, not a tuple

>>> T

>>> T= (3, ) # to construct a tuple, add a comma after the single element

>>> T

(3,)
>>> T1=3, # It also creates a tuple with single element

>>> T1

(3,)

8.2.2 Creating a tuple using tuple( ) constructor:

o It is also possible to use the tuple( ) constructor to create a tuple.

>>>T=tuple( ) # empty tuple

>>> T=tuple((45,3.9, 'k',22)) #note the double round-brackets


>>> T
(45, 3.9, 'k', 22)

>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')

>>> T3=('hello','python')
>>> T3
('hello', 'python')

8.2.3 Nested Tuples:

>>> T=(5,10,(4,8))

>>> T

(5, 10, (4, 8))

8.2.4 Creating a tuple by taking input from the user:

>>> T=tuple(input("enter the elements: "))

enter the elements: hello python

>>> T
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')

>>> T1=tuple(input("enter the elements: "))

enter the elements: 45678

>>> T1

('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits

To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.

>>> T1=eval(input("enter the elements: "))

enter the elements: 56789

>>> T1

56789 # it is not a list, it is an integer value

>>> type(T1)

<class 'int'>

>>> T2=eval(input("enter the elements: "))

enter the elements: (1,2,3,4,5) # Parenthesis is optional

>>> T2

(1, 2, 3, 4, 5)

>>> T3=eval(input("enter the elements: "))

enter the elements: 6, 7, 3, 23, [45,11] # list as an element of tuple

>>> T3

(6, 7, 3, 23, [45, 11])


8.3 Accessing Tuples:

Tuples are very much similar to lists. Like lists, tuple elements are also indexed.
Forward indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………

➢ The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) with
indexes.
➢ tuple-name[start:end] will give you elements between indices start to end-1.
➢ The first item in the tuple has the index zero (0).

Example:

>>> alpha=('q','w','e','r','t','y')

Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
Backward Index

>>> alpha[5]
'y'
>>> alpha[-4]
'e'
>>> alpha[46]
IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain unchanged
TypeError: 'tuple' object does not support item assignment

8.3.1 Difference between List and Tuple:

S. No. List Tuple

1 Ordered and changeable (Mutable) Ordered but unchangeable (Immutable)

2 Lists are enclosed in brackets. [] Tuples are enclosed in parentheses. ( )

3 Element can be removed. Element can’t be removed.


8.4 Traversing a Tuple:

Syntax:

for <variable> in tuple-name:

statement

Example:

Method-1

>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)

Output:
q
w
e
r
t
y

Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])

Output:
q
w
e
r
t
y

8.5 Tuple Operations:

➢ Joining operator +
➢ Repetition operator *
➢ Slice operator [:]
➢ Comparison Operator <, <=, >, >=, ==, !=
• Joining Operator: It joins two or more tuples.

Example:

>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)

>>> T1 + (34)
TypeError: can only concatenate tuple (not "int") to tuple

>>> T1 + (34, )

(25, 50, 75, 34)

• Repetition Operator: It replicates a tuple, specified number of times.

Example:

>>> T1*2

(25, 50, 75, 25, 50, 75)

>>> T2=(10,20,30,40)

>>> T2[2:4]*3

(30, 40, 30, 40, 30, 40)

• Slice Operator:

tuple-name[start:end] will give you elements between indices start to end-1.

>>>alpha=('q','w','e','r','t','y')

>>> alpha[1:-3]

('w', 'e')

>>> alpha[3:65]

('r', 't', 'y')

>>> alpha[-1:-5]
()

>>> alpha[-5:-1]

('w', 'e', 'r', 't')

List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.

>>> alpha[1:5:2]

('w', 'r')

>>> alpha[ : : -1]

('y', 't', 'r', 'e', 'w', 'q') #reverses the tuple

• Comparison Operators:

o Compare two tuples


o Python internally compares individual elements of tuples in lexicographical
order.
o It compares the each corresponding element must compare equal and two
sequences must be of the same type.
o For non-equal comparison as soon as it gets a result in terms of True/False,
from corresponding elements’ comparison. If Corresponding elements are equal,
it goes to the next element and so on, until it finds elements that differ.

Example:

>>> T1 = (9, 16, 7)


>>> T2 = (9, 16, 7)
>>> T3 = ('9','16','7')
>>> T1 = = T2
True
>>> T1==T3
False
>>> T4 = (9.0, 16.0, 7.0)
>>> T1==T4
True
>>> T1<T2
https://pythonschoolkvs.wordpress.com/ Page 32
False
>>> T1<=T2
True

8.6 Tuple Methods:

Consider a tuple:

subject=("Hindi","English","Maths","Physics")

S. Function
No.
Description Example
Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: >>> len(subject)
len (tuple-name) 4
2 max( ) Returns the largest value >>> max(subject)
from a tuple. 'Physics'
Syntax:
max(tuple-name)
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.

>>> subject = (15, "English", "Maths", "Physics", 48.2)


>>> max(subject)
TypeError: '>' not supported between instances of 'str' and 'int'

3. min( ) Returns the smallest >>>subject=("Hindi","English","Maths","Physics")


value from a tuple. >>> min(subject)
Syntax:
min(tuple-name) 'English'
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.

>>> subject = (15, "English", "Maths", "Physics", 48.2)


>>> min(subject)
TypeError: '>' not supported between instances of 'str' and 'int'

4 index( ) Returns the index of the >>>subject=("Hindi","English","Maths","Physics")

first element with the


specified value.
Syntax:

[Type here]
tuple- >>> subject.index("Maths")
name.index(element)
2
5 count( ) Return the number of >>> subject.count("English")
times the value appears.
Syntax: 1
tuple-
name.count(element)

8.7 Tuple Packing and Unpacking:

Tuple Packing: Creating a tuple from set of values.

Example:

>>> T=(45,78,22)
>>> T
(45, 78, 22)

Tuple Unpacking : Creating individual values from the elements of tuple.

Example:

>>> a, b, c=T
>>> a
45
>>> b
78
>>> c
22

Note: Tuple unpacking requires that the number of variable on the left side must be equal
to the length of the tuple.

8.8 Delete a tuple:

The del statement is used to delete elements and objects but as you know that tuples are
immutable, which also means that individual element of a tuple cannot be deleted.

[Type here]
Example:

>> T=(2,4,6,8,10,12,14)

>>> del T[3]

TypeError: 'tuple' object doesn't support item deletion

But you can delete a complete tuple with del statement as:

Example:

>>> T=(2,4,6,8,10,12,14)

>>> del T

>>> T

NameError: name 'T' is not defined

[Type here]
CHAPTER-9
DICTIONARY IN PYTHON

9.1 INTRODUCTION:

▪ Dictionary is a collection of elements which is unordered, changeable and indexed.


▪ Dictionary has keys and values.
▪ Doesn’t have index for values. Keys work as indexes.
▪ Dictionary doesn’t have duplicate member means no duplicate key.
▪ Dictionaries are enclosed by curly braces { }
▪ The key-value pairs are separated by commas ( , )
▪ A dictionary key can be almost any Python type, but are usually numbers or strings.
▪ Values can be assigned and accessed using square brackets [ ].

9.2 CREATING A DICTIONARY:

Syntax:

dictionary-name = {key1:value, key2:value, key3:value, keyn:value}

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

>>> D = { } #Empty dictionary

>>> D

{ }

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee that

# elements in dictionary can be accessed as per specific order.

[Type here]
Note: Keys of a dictionary must be of immutable types, such as string, number, tuple.

Example:

>>> D1={[2,3]:"hello"}

TypeError: unhashable type: 'list'

Creating a dictionary using dict( ) Constructor:

A. use the dict( ) constructor with single parentheses:

>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)

>>> marks

{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

➢ In the above case the keys are not enclosed in quotes and equal sign is used
for assignment rather than colon.

B. dict ( ) constructor using parentheses and curly braces:

>>> marks=dict({"Physics":75,"Chemistry":78,"Maths":81, "CS":78})

>>> marks

{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

C. dict( ) constructor using keys and values separately:

>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))

>>> marks

{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

[Type here]
In this case the keys and values are enclosed separately in parentheses and are given as
argument to the zip( ) function. zip( ) function clubs first key with first value and so on.

D. dict( ) constructor using key-value pairs separately:

Example-a

>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.

>>> marks

{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

Example-b

>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))

# tuple as argument passed to dict( ) constructor contains list type elements

>>> marks

{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

Example-c

>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))

# tuple as argument to dict( ) constructor and contains tuple type elements

>>> marks

{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

[Type here]
9.3 ACCESSING ELEMENTS OF A DICTIONARY:

Syntax:

dictionary-name[key]

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> marks["Maths"]

81

>>> marks["English"] #Access a key that doesn’t exist causes an error

KeyError: 'English'

>>> marks.keys( ) #To access all keys in one go

dict_keys(['physics', 'Chemistry', 'Maths', 'CS'])

>>> marks.values( ) # To access all values in one go

dict_values([75, 78, 81, 78])

Lookup : A dictionary operation that takes a key and finds the corresponding value, is

called lookup.

9.4 TRAVERSING A DICTIONARY:

Syntax:

for <variable-name> in <dictionary-name>:

statement

[Type here]
Example:

>>> for i in marks:

print(i, ": ", marks[i])

OUTPUT:

physics : 75

Chemistry : 78

Maths : 81

CS : 78

9.5 CHANGE AND ADD THE VALUE IN A DICTIONARY:

Syntax:

dictionary-name[key]=value

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

>>> marks['CS']=84 #Changing a value

>>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}

>>> marks['English']=89 # Adding a value

>>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}

[Type here]
9.6 DELETE ELEMENTS FROM A DICTIONARY:

There are two methods to delete elements from a dictionary:

(i) using del statement

(ii) using pop( ) method

(i) Using del statement:

Syntax:

del dictionary-name[key]

Example:

>>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}

>>> del marks['English']

>>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}

(ii) Using pop( ) method: It deletes the key-value pair and returns the value of deleted

element.

Syntax:

dictionary-name.pop( )

Example:

>>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}

>>> marks.pop('Maths')

81

[Type here]
9.7 CHECK THE EXISTANCE OF A KEY IN A DICTIONARY:

To check the existence of a key in dictionary, two operators are used:

(i) in : it returns True if the given key is present in the dictionary, otherwise False.

(ii) not in : it returns True if the given key is not present in the dictionary, otherwise

False.

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> 'Chemistry' in marks

True

>>> 'CS' not in marks

False

>>> 78 in marks # in and not in only checks the existence of keys not values

False

However, if you need to search for a value in dictionary, then you can use in operator
with the following syntax:

Syntax:

value in dictionary-name. values( )

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> 78 in marks.values( )

True

9.8 PRETTY PRINTING A DICTIONARY:

What is Pretty Printing?

[Type here]
To print a dictionary in more readable and presentable form.

For pretty printing a dictionary you need to import json module and then you can use

dumps( ) function from json module.

Example:

>>> print(json.dumps(marks, indent=2))

OUTPUT:

"physics": 75,

"Chemistry": 78,

"Maths": 81,

"CS": 78

dumps( ) function prints key:value pair in separate lines with the number of spaces

which is the value of indent argument.

9.9 COUNTING FREQUENCY OF ELEMENTS IN A LIST USING DICTIONARY

Steps:

1. import the json module for pretty printing


2. Take a string from user
3. Create a list using split( ) function
4. Create an empty dictionary to hold words and frequency
5. Now make the word as a key one by one from the list
6. If the key not present in the dictionary then add the key in dictionary and count
7. Print the dictionary with frequency of elements using dumps( ) function.

[Type here]
Program:

import json

sentence=input("Enter a string: ")

L = sentence.split()

d={ }

for word in L:

key=word

if key not in d:

count=L.count(key)

d[key]=count

print("The frequqency of elements in the list is as follows: ")

print(json.dumps(d,indent=2))

9.10 DICTIONARY FUNCTIONS:

Consider a dictionary marks as follows:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

S. Function
No.
Description Example
Name
1 len( ) Find the length of a >>> len(marks)
dictionary.
Syntax: 4
len (dictionary-name)
2 clear( ) removes all elements >>> marks.clear( )
from the dictionary
Syntax: >>> marks
dictionary-name.clear( )
{}

[Type here]
3. get( ) Returns value of a key. >>> marks.get("physics")
Syntax:
dictionary-name.get(key) 75

Note: When key does not exist it returns no value without any error.

>>> marks.get('Hindi')

>>>
4 items( ) returns all elements as a >>> marks.items()
sequence of (key,value)
tuples in any order. dict_items([('physics', 75), ('Chemistry',
Syntax: 78), ('Maths', 81), ('CS', 78)])
dictionary-name.items( )
Note: You can write a loop having two variables to access key: value pairs.
>>> seq=marks.items()
>>> for i, j in seq:
print(j, i)
OUTPUT:
75 physics
78 Chemistry
81 Maths
78 CS
5 keys( ) Returns all keys in the >>> marks.keys()
form of a list.
Syntax: dict_keys (['physics', 'Chemistry',
dictionary-name.keys( ) 'Maths', 'CS'])
6 values( ) Returns all values in the >>> marks.values()
form of a list.
Syntax: dict_values([75, 78, 81, 78])
dictionary-name.values( )
7 update( ) Merges two dictionaries.
Already present elements
are override.
Syntax:
dictionary1.update(dictionary2)
Example:
>>> marks1 = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks2 = { "Hindi" : 80, "Chemistry" : 88, "English" : 92 }
>>> marks1.update(marks2)
>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81, 'CS': 78, 'Hindi': 80, 'English': 92}
[Type here]
CHAPTER-10
SORTING

10.1 DEFINITION:

To arrange the elements in ascending or descending order.

In this chapter we shall discuss two sorting techniques:


1. Bubble Sort
2. Insertion Sort

1. BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons, in


which each element is compared to its adjacent element and the elements are swapped if they
are not in proper order.

[Type here]
PROGRAM:

L=eval(input("Enter the elements:"))

n=len(L)

for p in range(0,n-1):

for i in range(0,n-1):

if L[i]>L[i+1]:

L[i], L[i+1] = L[i+1],L[i]

print("The sorted list is : ", L)

OUTPUT:

Enter the elements:[60, 24, 8, 90, 45, 87, 12, 77]

The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]

Calculating Number of Operations (Bubble sort):

Step CODING No. of Operations


1 L=eval(input("Enter the elements:")) 1
2 n=len(L) #for example n=7 1
3 for p in range(0,n-1): one operation for each pass (executes 6 times, 0 to 5)

4 for i in range(0,n-1): executes 6 times for elements, same will repeat 6


times under each pass (outer loop) so 6x6=36
operations

5 if L[i]>L[i+1]: executes 6 times for comparisons in each pass, same


will repeat 6 times under each pass (outer loop) so
6x6=36 operations

6 L[i], L[i+1] = L[i+1],L[i] statement related to step-5, so 6x6=36 operations

7 print("The sorted list is : ", L) 1


TOTAL: 1+1+6+36+36+36+1=117 operations

[Type here]
2. INSERTION SORT: Sorts the elements by shifting them one by one and inserting the
element at right position.

PROGRAM:

L=eval(input("Enter the elements: "))

n=len(L)

for j in range(1,n):

temp=L[j]

prev=j-1

while prev>=0 and L[prev]>temp: # comparison the elements

L[prev+1]=L[prev] # shift the element forward

prev=prev-1

L[prev+1]=temp #inserting the element at proper position

print("The sorted list is :",L)

[Type here]
OUTPUT:

Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]

The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]

[Type here]

You might also like