0% found this document useful (0 votes)
2 views

unit-3 python

This document covers the use of string data types and operations in Python, explaining string creation, indexing, slicing, and manipulation methods. It also introduces lists and tuples, detailing their creation, indexing, and various operations, including adding and removing elements. Additionally, it discusses sets, their properties, and built-in functions for managing sets in Python.
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)
2 views

unit-3 python

This document covers the use of string data types and operations in Python, explaining string creation, indexing, slicing, and manipulation methods. It also introduces lists and tuples, detailing their creation, indexing, and various operations, including adding and removing elements. Additionally, it discusses sets, their properties, and built-in functions for managing sets in Python.
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/ 41

UNIT 3

Lecture 12. Use of string data type & string operations.

3.1 String

● A String is a data structure in Python that represents a sequence of characters.


● It is an immutable data type, meaning that once you have created a string, you cannot
change it.
● Strings are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be represented
as text.
Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. Python does not have a character data type, a single character is simply a string
with a length of 1.
3.1.1 Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string or
docstrings.

# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

41
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life

3.1.3 Accessing characters in Python String


● In Python, individual characters of a String can be accessed by using the method of Indexing.
● Indexing allows negative address references to access characters from the back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.
● While accessing an index out of the range will cause an IndexError. Only Integers are allowed
to be passed as an index, float or other types that will cause a TypeError.

3.1.4.String Slicing
● In Python, the String Slicing method is used to access a range of characters in the String. Slicing
in a String is done by using a Slicing operator, i.e., a colon (:).
● One thing to keep in mind while using this method is that the string returned after slicing
includes the character at the start index but not the character at the last index.

Figure 3.1 String Slicing

42
Figure 3.2 String Slicing

3.1.5 Reassigning Strings


As Python strings are immutable in nature, we cannot update theexisting string. We can only assign
a completely new value to the variable with the samename.

Consider the following example.

Example 1

Output:

A character of a string can be updated in Python by first converting the string into a Python List and then
updating the element in the list. As lists are mutable in nature, we can update the character and then convert
the list back into the String.

# Python Program to Update


# character of a String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

43
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#way1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)

#way 2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)

Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek

3.1.6 Deleting the String

As we know that strings are immutable. We cannot delete or remove the characters from
the string. But we can delete the entire string using the del keyword.

Output:

Now we are deleting entire string.

Output:

44
3.1.7 Escape Sequencing in Python
● While printing Strings with single and double quotes in it causes SyntaxError
because String already contains Single and Double Quotes and hence cannot be printed
with the use of either of these.

● Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and the same is done for Double Quotes.

Example
String1= "C:\\Python\\Geeks\\"
print(String1)

3.1.8 Formatting of Strings


Strings in Python can be formatted with the use of format( ) . Format method in String
contains curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.

String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')


print("\nPrintString in order of Keywords: ")

print(String1)
Output

Print String in order of Keywords:


Life For Geeks

45
Letcure 13. Python List & List Slicing
3.2 List-
● The list is a sequence data type which is used to store the collection of data.
● In lists the comma (,)and the square brackets [enclose the List's items] serve as separators.
● Lists need not be homogeneous always which makes it the most powerful tool in Python.
● A single list may contain DataTypes like Integers, Strings, as well as Objects.
● Lists are mutable, and hence, they can be altered even after their creation.

3.2.1 Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square brackets[].

A list may contain duplicate values with their distinct positions and hence, multiple distinct or
duplicate values can be passed as a sequence at the time of list creation.

Example-

List1=[“physics”, “Maths”,34,15.5]
List2=[2,3,5,10]

3.2.2 List Indexing and Splitting

The indexing procedure is carried out similarly to string processing. The slice operator [] can be
used to get to the List's components.

The index ranges from 0 to length -1.

Figure 3.3 List Slicing

46
We can get the sub-list of the list using the following syntax.

o The beginning indicates the beginning record position of the rundown.

o The stop signifies the last record position of the rundown.

o Within a start, the step is used to skip the nth element: stop.
Example-
List1=[0,1,2,3,4]
List1[1:3:1]= [1,2]

3.2.3 Adding Elements to a Python List

Method 1: Using append() method -


Only one element at a time can be added to the list by using the append() method

List = []
print("Initial blank List: ")
print(List)

List.append(1)
List.append(2)
print("List after Addition of Three elements: ")
print(List)

Method 2: Using insert() method-


append() method only works for the addition of elements at the end of the List, forthe
addition of elements at the desired position insert() method is used.

List.insert(2, 12)

print("List after performing Insert Operation: ")


print(List)

Method 3: Using extend() method-


47
Extend( ) method is used to add multiple elements at the same time at the end ofthe list.

List.extend([8, 'Geeks'])
print("List after performing Extend Operation: ")
print(List)

3.2.4 Removing Elements from the List

Method 1: Using remove() method

Elements can be removed from the List by using the built-in remove() function but an
Error arises if the element doesn’t exist in the list.

List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]


List.remove(5)
List.remove(6)
print("List after Removal of two elements: ")
print(List)
Method 2: Using pop() method
pop() function can also be used to remove and return an element from the list, but by default
it removes only the last element of the list, to remove an element from a specific position of
the List, the index of the element is passed as an argument to the pop() method.

List = [1, 2, 3, 4, 5]
List.pop()
print("List after popping an element: ")
print(List)
List.pop(2)
print("\nList after popping a specific element: ")
print(List)

48
3.3 List Operations-

Table 3.1 List Operations

3.4 List out some in-built function in python List

Table 3.2 List In Built Function

49
3.5 List Built In Methods-

Table 3.3 List InBuilt Methods

50
51
Lecture 14. How to Use of Tuple data type
3.6 Tuple

Note: Creation of Python tuple without the use of parentheses is known as TuplePacking.

52
Note: We can change any python collection like (list, tuple, set) and string into other data
type like tuple, list and string. But cannot change into and float to any python collection. For
example: int cannot change into list or vice-versa.

Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple
gets deleted by the use of del() method.

Note- Printing of Tuple after deletion results in an Error.


Python

Traceback (most recent call last):


File “/home/efa50fd0709dec08434191f32275928a.py”, line 7, in
print(Tuple1)
NameError: name ‘Tuple1’ is not defined

53
3.6.1 Tuple Operations

Table 3.4 Tuple Operations

3.6.2 Tuple Built-in Functions

Table 3.5 Tuple Built-in Functions

54
3.7 The zip() Function
The zip() is an inbuilt function in python. It takes items in sequence from a number of
collections to make a list of tuples, where each tuple contains one item from each collection.
The function is often used to group items from a list which has the same index.

Example:
A=[1,2, 3]
B=’XYZ’
Res=list(zip(A,B)) # list of tuples
print(Res)
Output:
[(1, 'X'), (2, 'Y'), (3, 'Z')]

We can change into tuple of tuples


Res=tuple(zip(A,B))
# tuple of tuples
Note: if the sequences are not of the same length then the result of zip() has the length of
the shorter sequence.
A=’abcd
B=[1,2,3]
Res=list(zip(A,B))
print(Res)
Output:
[(‘a’,1),(‘b’,2),(‘c’,3)]

The Inverse zip(*) Function


The * operator is used within the zip() function. The * operator unpacks a sequence into
positional arguments.
X=[(‘apple’,90000),(‘del’,60000),(‘hp’,50000)]
Laptop,prize=zip(*X)
print(Laptop)
print(prize)
Output:
(‘apple’,’del’,’hp’)
(90000,60000,50000)

55
Python program to find the maximum and minimum K elements in a tuple

Output

56
Lecture 15. String and string manipulation methods.
3.8 string manipulation methods-

capitalize() Converts the first character to upper case

count() Returns the number of times a specified value occurs in a string

endswith() Returns true if the string ends with the specified value

find() Searches the string for a specified value and returns the position of where
it was found

format() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where
it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

islower() Returns True if all characters in the string are lower case

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

57
isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

split() Splits the string at the specified separator, and returns a list

replace() Returns a string where a specified value is replaced with a specified


value

startswith() Returns true if the string starts with the specified value

title() Converts the first character of each word to upper case

upper() Converts a string into upper case

lower() Converts a string into lower case

swapcase() Swaps cases, lower case becomes upper case and vice versa

Table 3.6 string manipulation methods

Programs on Python Strings

1. WAP to display unique words from the string

str=input("Enter string:") l=str.split()


l1=[]
for i in l:
if i not in l1:
l1.append(i)
str=" ".join(l1)
print(str)

2. WAP to accept a string & replace all spaces by # without using string method.

str=input("Enter string:") str1=""


for i in str:
if i.isspace():
str1+="#
else:
str1+=i
print(“output is”,str1)

58
Lecture 16 Python Set and list manipulating methods
3.9 Set- set is an unordered collection of data items which does not contain duplicate values.
Every set element is unique and must be immutable (cannot be changed). However, a set
itself is mutable. Elements of set are enclosed inside a pair of curly brackets {}.

We can add and remove items from the set. But cannot replace item as it does not support
indexing of data items.
Empty set is created by:
A=set()
print(A)
Outpu t:
Set()

Output:
apple
banan a
cherry

59
NOTE: Lists cannot be added to a set as elements because Lists are not hashable whereas
Tuples can be added because tuples are immutable and hence Hashable.

Removing elements from the Set

Using remove() method or discard() method:

● Elements can be removed from the Set by using the built-in remove() function but
a KeyError arises if the element doesn’t exist in the set.

● To remove elements from a set without KeyError, use discard(), if the element
doesn’t exist in the set, it remains unchanged.

60
Note: If the set is unordered then there’s no such way to determine which
element is popped by using the pop() function.

Python Set in -built functions:

61
Examples:

S1={1,2,3,4,5}
S1.remove(2)
print(S1)
Output:
{1,3,4,5}

S1={1,2,3,4}
S2={1,2,3,4,5}

print(S1.issubset(S2))
Output:
True

print(S2.issuperset(S1))
Output:
True

>>>
S1={1,2,3,4,5}
S2={5,6,7}
print(S1.union(S2)) #
print(S1|S2)
Output:
{1,2,3,4,5,6,7}

>>>

print(S1.intersection(S2)) #
print(S2&S2)
Output:
{5}

>>>

print(S1.difference(S2))
print(S1-S2)
Output:
{1,2,3,4}

62
>>>
print(S1.symmetric_difference(S2))
print(S1^S2)

Output:
{1,2,3,4,6,7}

3.10 List manipulating method

Table 3.7 List Buit-in Methods

63
Lecture 17. Python Dictionary and its manipulation method

3.11 Dictionary in Python


It is a collection of keys values, used to store data values like a map, which, unlike other data
types which hold only a single value as an element.
Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is written
with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can
be of any type, but the keys must be of an immutable data type such as strings, numbers, or
tuples.

3.11.1 Properties of Dictionary Keys


There are two important points to remember about dictionary keys −
More than one entry per key is not allowed. Which means no duplicate key is allowed. When
duplicate keys are encountered during assignment, the last assignment wins.
Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary
keys but something like ['key'] is not allowed.

3.11.2 Accessing value to a dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. . Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print("dict['Name']:",dict['Name'])
print("dict['Age']: ", dict['Age'])

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


dict['Name']:Zara
dict['Age']: 7

There is also a method called get() that will also help in accessing the element from a
dictionary.This method accepts key as argument and returns the value.

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


print("Accessing a element using get:")
print(Dict.get(3))

3.11.3 Updating Dictionary


64
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry as shown below in the simple example –

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.update({"color": "White"})

print(car)Deleting Elements using del

Keyword
The items of the dictionary can be deleted by using the del keyword

Output

Dictionary ={1: 'Geeks', 'name': 'For', 3:


'Geeks'}
Data after deletion
Dictionary={'name': 'For', 3: 'Geeks'}

3.12 Built-in Dictionary Functions & Methods


Python includes the following dictionary functions –

Sr.No. Function with Description

65
cmp(dict1, dict2)
1
Compares elements of both dict.
len(dict)
2 Gives the total length of the dictionary. This would be equal to the number
of items in the dictionary.
str(dict)
3
Produces a printable string representation of a dictionary
type(variable)
4
Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.

Figure 3.8 Dictionary Functions

3.13 Dictionary methods

Method Description

Remove all the elements from the dictionary


dict.clear()

dict.copy() Returns a copy of the dictionary

dict.get(key, default = “None”) Returns the value of specified key

Returns a list containing a tuple for


each key value pair
dict.items()

dict.keys() Returns a list containing dictionary’s keys

Updates dictionary with specified key-


dict.update(dict2)
value pairs

dict.values() Returns a list of all the values of dictionary

pop() Remove the element with specified key

popItem() Removes the last inserted key-value pair

set the key to the default value if the


dict.setdefault(key,default= “None”)
key is not specified in the dictionary
66
returns true if the dictionary contains
the specified key.
dict.has_key(key)

used to get the value specified for the


dict.get(key, default = “None”) passed key.

67
Lecture 18. Function

3.15 Function.

Program for sum of digits from range x to y def sum(x,y): –>

Master code
def sum(x,y):

s=0

for i in range(x,y+1):
s-s+i

print(“sum of integers from x to y :”,s)


sum(50,75) –> Driver code

Output:
sum of integers from x to y : 1625
Function calling is called driver code and function definition with block of statements is called master
code

68
3.16 Differentiate between argument and parameter.

Ans: Parameters are of two types:

• Formal parameter
• Actual Parameter
Formal parameters are those written in function definition and actual
parameters are those written in function calling.
Formal parameters are called argument.
Arguments are the values that are passed to function definition.
Example:
Def fun(n1):
Print(n1)
a=10
fun(a)
here n1 is argument and a is parameter.

3.17 Different types of arguments in python.

Ans:

69
70
def display(a='hello',b='world'): # you can have only default arguments

print(a,b)

display()

Output:

hello world

71
def display(a,c=10,b): # default argument will always come as last argument
d=a+b+c

print(d)

display(2,3) # error, non default argument follows default argument

def display(a,b,c=10):
d=a+b+c

print(d)

display(2, 3)

Output:
15

Variable length with first extra argument:

72
variable length argument Example:

def display(*arg):

for i in arg:

print(i)

display(‘hello’,’world’)
Output:

hello

world

3.18 Return statement:

73
The Return Statement:The return statement is used to return a value from the function to a
calling function. It is also used to return from a function i.e. break out of the function.
Example:

Program to return the minimum of two numbers:


Returning multiple values: It is possible in python to return multiple values def
compute(num):
return num*num,num**3
# returning multiple value

square,cube=compute(2)

print(“square = “,square,”cube =”,cube)

74
Lecture 19. Anonymous function
3.19 Anonymous Function

75
Program to find cube of a number using lambda function

cube=lambda x:
x*x*x

print(cube(2))

Output:
8

Note:
● The statement cube=lambda x: x*x*x creates a lambda function called cube, which
takes a single argument and returns the cube of a number.

● Lambda function does not contain a return statements


● It contains a single expression as a body not a block of statements as a body

Q6. Define scope of a variable. Also differentiate local and global variable.

Ans:

76
1. Program to access a local variable outside a functions
def demo():
q=10
print("the value of local variable is",q)

demo()

print("the value of local variable q is:",q)


#error, accessing a local variableoutside the scope will cause an error
Output:

the value of local variable is 10


Traceback (most recent call last):

File "C:/Users/Students/AppData/Local/Programs/Python/Python38-32/vbhg.py", line 5, in


<module>
print("the value of local variable q is:",q)

NameError: name 'q' is not defined

2. Program to read global variable from a local scope


def demo():
print(s)

s=’I love python’

77
demo()

Output:

I love python

3. Local and global variables with the same name


def demo():

s=’I love

python print(s)

s=’I love programming’

demo() # first function is called, after that other satements print(s)

Output:
I love python

I love programming

The Global Statement


Global statement is used to define a variable defined inside a function as a global variable. To
make local variable as global variable, use global keyword

Example:
a=20

def display():

global a
a=30

print(‘value of a is’,a)

display()

print(‘the value of an outside function is’,a)

Output:
value of a is 30

the value of an outside function is 30

Note:
Since the value of the global variable is changed within the function, the value
of ‘a’ outside the function will be the most recent value of ‘a’

78
Lecture 20. Recursion Function

3.20 Recursion-

Q Program to find the factorial of a number using recursion

def factorial(n):

if n==0: # base condition

return 1
return n * factorial(n-1)
print(factorial(5))

Output:

120

Note: Recursion ends when the number n reduces to 1. This is called base condition. Every
recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely.

Q8. Program to find the fibonacci series using recursion.

Ans:

def fibonacci(n):
if(n <= 1):
79
return n

else:
return(fibonacci(n-1) + fibonacci(n-2))

n = int(input("Enter number of terms:"))

print("Fibonacci sequence:")

for i in range(n):

print(fiboncci(i)
,

Q9. Program to find the GCD of two numbers using recursion.

Ans:

def gcd(a,b):
if(b==0):

returna
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))

b=int(input("Enter second number:"))

GCD=gcd(a,b)

print("GCD is: )

print(GCD)

Q10. Program to find the sum of elements in a list recursively.

Ans:
def sum_arr(arr,size):
if (size == 0):
return 0
else:

return arr[size-1] + sum_arr(arr,size-1)


n=int(input("Enter the number of elements for list:"))
a=[]

80
for i in range(0,n):
element=int(input("Enter element:"))
a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")

b=sum_arr(a,n)

print(b)

Q11. Program to check whether a string is a palindrome or not using recursion. Ans:

def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))

if(is_palindrome(a)==True):

print("String is a palindrome!")

else:

print("String isn't a palindrome!")

Important Ques Unit-3


i. Explain mutuable sequences in python .(2019-20,2023-24)
ii. Compare list and tuple with suitable example. Explain the concept of list
comprehension.(2019-20)
iii. Write a python program that accepts a sentence and calculate the number of digits.
Uppercase and lowercase letters. (2021-22)
iv. Write a program to print fibonnacci series upto n terms using user-defined function
(2021-22)
v. Explain output of following function . (2022-23)
def printalpha(abc_list , num_list):

for char in abc_list:


for num in num_list:
print(char, num)
return
printalpha(['a','b','c'],[1,2,3])

81

You might also like