0% found this document useful (0 votes)
2 views52 pages

String Material

Chapter 2 introduces Python as a programming language created by Guido Van Rossum in 1991, highlighting its features such as simplicity, expressiveness, and support for object-oriented programming. It covers Python's installation, execution modes, and basic terminology including variables, keywords, and identifiers. Additionally, Chapter 5 focuses on string manipulation, detailing string creation, indexing, slicing, and built-in functions for string operations.

Uploaded by

nikhileshmgouri8
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 views52 pages

String Material

Chapter 2 introduces Python as a programming language created by Guido Van Rossum in 1991, highlighting its features such as simplicity, expressiveness, and support for object-oriented programming. It covers Python's installation, execution modes, and basic terminology including variables, keywords, and identifiers. Additionally, Chapter 5 focuses on string manipulation, detailing string creation, indexing, slicing, and built-in functions for string operations.

Uploaded by

nikhileshmgouri8
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

Chapter-2

Getting Started with Python


What is a program and programming language?
An ordered set of instructions to be executed by a computer to carry out specific task is called as
a program, and the language used to specify this set of instructions to the computer is called a
programming language.
Introduction to Python:
Python was developed by ‘Guido Van Rossum’ in 1991. Python Programming Language uses an
interpreter to convert its instructions into machine language, so that it can be understood by the
computer.

Note: Interpreter converts high level language to low level language line by line.

Features of Python:
Easy: Python is simple and easy to learn and code. Its syntax is almost English-like.
Expressive: Easy syntax and fewer syntactical constructions make python an expressive language.
Free and open source: Python is a free and open-source language, as you can download and
install it in your computer without paying any fee.
High-level Language: Python is a high-level language because it has all the features of a high-level
language. Its English-like syntax makes it easy to read and write. It is easy to find errors and debug
Python programs.
Portable: Python is a platform-independent language. Python programs can run on any platform
without making any changes to them.
Object Oriented: Python supports object-oriented programming (OOP) principles such as
encapsulation (bundling of data (attributes) and methods (functions)), inheritance (inheriting the
properties and behaviours of an existing class (base class or superclass)), and polymorphism (take
multiple forms). Everything in Python is an object, which allows for modular and reusable code.
Interpreted: Python uses an interpreter (Known as Python Virtual Machine) to convert the code
and run on any platform.
Extensive Libraires: The Python Libraries is a collection of functions that you can add in your
program. It helps to make Python programs simple and easy.
Dynamically-Typed Language: Python is dynamically typed language. It means you do not need to
declare the type of variables before their use while programming.

Uses of Python:
Python is used in many domains as listed below:
1. Web and Internet Development: Python has huge built in library that supports internet
protocols and offers many choices for web development.
2. Scientific and Numeric Computing: Python is widely used to compute scientific and numeric
problems as it has a huge library of mathematics and data analysis packages.
3. Desktop GUIs: Python is also used to build desktop GUIs and applications using various toolkits.
4. Software Development: Software developers are using python to develop various tools and
software.
5. Business Applications: Python is used to build ERP (Enterprise Resource Planning) and e-
commerce systems that can be used with huge data and can solve complex problems.
Python Installation: Python can be directly downloaded and installed from the website:
[Link]
Execution Modes of Python:
There are Two ways to use the python interpreter:
1. Interactive mode (Python IDLE (Integrated Development and Learning Environment)):
In the interactive mode, we can simply type a python statement on the >>> prompt directly. As
soon as we press enter, the interpreter executes the statement and displays the result/s. This mode
is convenient for testing a single line code for instant execution. But in the interactive mode, we
cannot save the statements for future use and we have to retype the statements to run them again.

2. Script Mode: In the script mode, we can write a python program in a file, save it and then use
the interpreter to execute it. Python files has an extension “.py”. To execute the python program in
script mode click Run→ Run Module from menu or press F5 from the keyboard.

Python Terminology.
Keywords: Keywords are reserved words, each keyword has a specific meaning to the python
interpreter, and we can use a keyword in our program only for the purpose for which it has been
defined.
Examples: if, elif, do, while, print, not in, in…….
Identifiers: Identifiers are names used to identify a variable, function or other entities in a program.
The naming conventions of identifiers in python are as follows.
1. An identifier cannot start with a digit.
2. Keywords cannot be used as identifiers.
3. We cannot use special symbols like! @, #, $, %.... etc as identifiers. (Only underscore is allowed)
Examples of valid identifiers.
1. num1
2. percentage
3. student_mark
Examples of invalid identifiers.
1. 1_num
2. marks@grade11
3. pass
Variables: Variable in python refers to an object- an item or element that is stored in the memory.
Value of a variable can be a
String: ‘b’, ‘global citizen’
Numeric: 123
Alphanumeric:CD123
Variable declaration is implicit in python, which means variables are automatically declared and
defined when they are assigned a value for the first time. Variables must always be assigned values
before they are used in expressions otherwise it will lead to an error in the program.
Example1: Write a program to store the names of three students and display them.
Method1: Script Mode Aman
name1="Aman" Amit
name2="Amit" Sumit
name3="Sumit"
print(name1)
print(name2)
print(name3)
Method2: Interactive Mode
>>> name1="Aman"
>>> name2="Amit"
>>> name3="Sumit"
>>> print(name1)
Aman
>>> print(name2)
Amit
>>> print(name3)
Sumit
>>>
Example 2: Write a program to display the sum of two numbers:
Method1: Script Mode 50
num1=20
num2=30
s=num1+num2
print(s)
Method2: Interactive Mode
>>> num1=20
>>> num2=30
>>> s=num1+num2
>>> print(s)
50
>>> print(num1+num2)
50
Comments: Comments are used to add a remark or note in the source code. Comments are not
executed by interpreter. They are added with the purpose of making the source code easier for
humans to understand. In python, a comment starts with # (Hash Sign)
Chapter-5
String Manipulation
Handout
String: In Python, a string is a sequence of characters or symbols enclosed within single quotes (')
or double quotes ("). It is a fundamental data type used to represent textual data.
Creating Python Strings: As long as the same sequence of characters is enclosed, single or double
or triple quotes don't matter. Hence, following string representations are equivalent.
Example:
>>> 'Welcome To PES Public School'
'Welcome To PES Public School '
>>> "Welcome To PES Public School
'Welcome To PES Public School
>>> '''Welcome To PES Public School '''
'Welcome To PES Public School '
>>> """Welcome To PES Public School"""
'Welcome To PES Public School'
A string stores all the elements in memory and assigns an index value or position -id to it, which
can be used to access its individual characters.
In python, the string data type is an ordered sequence of character data. Elements of a string can
be accessed by using index vales.
The process of storing and retrieving elements of an ordered data type using index or key values
is called INDEXING.
Index values are numeric, either positive or negative.
Characters of a string are held in continuous memory locations. These memory locations are
indicated by indices.
For example, consider the string msg=’BOTTLE’ and observe the location of its elements in the
memory.

Positive
0 1 2 3 4 5
Indexing
List
B O T T L E
Elements
Negative
-6 -5 -4 -3 -2 -1
Indexing

Square brackets [] can be used to access characters of the string. Individual characters in a string
can be accessed by specifying the string name followed by its index number in the square
brackets [].
Accessing Values in Strings: Python does not support a character type; these are treated as
strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain
your substring.
For example:
var1 = 'Hello World!' Output:
var2 = "Python Programming" var1[0]: H
print ("var1[0]: ", var1[0]) var2[1:5]: ytho
print ("var2[1:5]: ", var2[1:5])

String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then –
>>>a='Hello'
>>>b= 'Python'
Operator Description Example

Concatenation - Adds values on either side of the operator a + b will give


+
HelloPython

Repetition - Creates new strings, concatenating multiple copies a*2 will give -
*
of the same string HelloHello

Slice - Gives the character from the given index a[1] will give
[]
e

Range Slice - Gives the characters from the given range a[1:4] will give
[:]
ell

Membership - Returns true if a character exists in the given H in a will give


in string
1

Membership - Returns true if a character does not exist in the M not in a will
not in given string give
1

Raw String - Suppresses actual meaning of Escape characters. print r'\n' prints
The syntax for raw strings is exactly the same as for normal \n and print
strings with the exception of the raw string operator, the letter R'\n'prints \n
r/R
"r," which precedes the quotation marks. The "r" can be
lowercase (r) or uppercase (R) and must be placed immediately
preceding the first quote mark.

Format - Performs String formatting See at next


%
section
Concatenation: In Python, string concatenation refers to joining two strings or joining characters
one after another. The plus (+) operator is used to perform string concatenation.
For example:
>>> a='hello'
>>> b='world'
>>> print(a+b)
helloworld
Program-1: Write a program that accepts the first name and last name from the user and display
full name.

fname=input("Enter your first name ") Enter your first name Ravi
lname=input("Enter your last name ") Enter your last name Kiran
print(fname+' '+lname) Ravi Kiran
Note: Concatenation operations can only be performed on strings.
Repetition: A string can be repeated a specific number of times using the repetition operator (*).
The * operator makes multiple copies of a sequence and joins them together. The * operator is
also called the multiplication operator, which is used to multiply two numeric values and display
the result. On String, it acts differently and multiplies the sequence with given number of times.
For example,

>>> a='hello' >>> c="3" >>> print("Hi" * "Hello")


>>> print(a*3) >>> print(c*3) TypeError: can't multiply
Hellohellohello 333 sequence by non-int of type
>>> print(8*2) 'str'
16
Program-2: Write a program that accepts the first name and last name of a user, joins them as
full name with space, and displays “ Welcome + full name” 5 times.

fname=input("Enter your first name ") Enter your first name Ravi
lname=input("Enter your last name ") Enter your last name Kiran
print(("Welcome" +fname+' '+lname)*5) WelcomeRavi KiranWelcomeRavi
KiranWelcomeRavi KiranWelcomeRavi
KiranWelcomeRavi Kiran
Using Membership Operators: Membership operators are used to test the presence of an element
in a string. There are two types of membership operators.
1. “in” operator: The membership operator ‘in’ is used to check if a value exists in a sequence or
not. If it finds the element in the sequence, then it returns True, otherwise it will return False.
2. ‘not in’ operator: The not in operator returns True if it does not find the element in sequence,
otherwise it returns False.
Example:

>>> "h" in "hey" >>> "H" in "hey"


True False
>>> "he" in "hey" >>> "HE" in "hey"
True False
Program-3: Write a program to input an integer and check if it contains any 0 in it.

n=int(input("Enter a Number: ")) Enter a Number: 1234


s=str(n) There is a no 0 in 1234
if '0' in s:
print("There is a 0 in", n) Enter a Number: 21042
else: There is a 0 in 21042
print("There is a no 0 in", n)

Slicing: A slice means ‘a part of’ something. Similarly, python allows you to fetch a substring from
a string. A substring or a part of string can be accessed by using the slicing operator colon (:).
An expression of the form s[m:n] returns the substring or a part of the string S starting with index
m, and display up to n-1( not including the character at index n).
Example:

Slicing Output Explanation


print(s[5]) t Prints the character at index 5.
print(s[:5]) Hones Slices from the start of the string to index 5.
print(s[0:]) Honest Slices from index 0 to the end of the string.
print(s[2:5]) nes Slices from index 2 to 5.
print(s[2:6]) nest Slices from index 2 to 6.
print(s[0:3]) Hon Slices from index 0 to 3.
print(s[:]) Honest Slices the entire string.
print(s[::]) Honest Slices the entire string with no step modification.
sequence[start:stop:step]
print(s[0:5:2]) Hns The slicing s[0:5:2] selects characters from index 0 to 5, but with a
step of 2. This means it will pick every second character in the
range.
Negative Indexing: It is used to perform string slicing. Here, -1 refers to the last character, -2 the
second to- last, and so on.
Example:

Slicing Output
print(s[-5]) O
print(s[:-5]) H
print(s[::-1]) tsenoH
print(s[-3:-1]) es
print(s[-1:-6:-2]) teo
Program-4: Write a program that obtains a string from the user and displays it in reverse order.

s=input("Enter String: ") Enter String: Components of range(-1, -length-1, -1):


length=len(s) Honest -1: The loop starts at index -1, which is the last
element of a sequence (in Python, negative
for i in range(-1,-length-1,-1): t indices count from the end).
print(s[i]) s -length-1: The loop continues until the index -
e length-1. This is essentially before the start of the
n sequence.
o For example, if length = 5, this becomes -6.
-1: The step value is -1, meaning the loop will go
H backwards, decrementing by 1 with each
iteration.
Traversing strings using loops: Traversing means visiting the characters of the strings at least
once. The traversal starts at the beginning selects each character, performs the operation, and
continues doing so until the end. This pattern of processing is called traversal. The index value,
either positive or negative, can be used to traverse the string either from left-to-right or right-to-
left.

fruit='orange' o
index=0 r
while index<len(fruit): a
c=fruit[index] n
print(c) g
index=index+1 e
String Built-in-Functions: Python has a wide range of built-in functions or methods that can be
used with strings.
1. len(): python len() function can be used to find the length of a given string. It takes the name of
the string as a parameter and returns the length of the string as a numeric value.
Syntax: len(string)
Example:
name='guido van rossum'
l=len(name)
print(l)
output: 16
2. capitalize(): This function converts the first letter of the string to a capital letter.
Syntax: [Link]()

[Link] Example Output


1 >>> s='green' Green
>>> print([Link]())
2 >>> s='Red' Red
>>> print([Link]())
3 >>> s='be happy' Be happy
>>> print([Link]())
4 >>> s=' be happy' be happy
>>> print([Link]())
3. find(): This function checks if a substring is present in the string or not. It traverses the string
from the beginning to the end and returns the index of the first letter if the substring is found in
the string. Otherwise, if the substring is not present, then it returns-1.
Syntax: [Link](sub,[start,[end]])
Where
Sub: it is the string that can be searched.
Start: it is the starting index. By default, it is 0
End: it is the ending index, by default it is equal to the length of the string.
[Link] Example Output
1 >>> s='be happy' 4
>>> f=[Link]('a',0,len(s))
>>> print(f)
2 >>> f=[Link]('hap',0,len(s)) 3
>>> print(f)
3 >>> f=[Link]('d',0,len(s)) -1
>>> print(f)
4 >>> f=[Link]('hat',0,len(s)) -1
>>> print(f)
Chapter-6
List Manipulation
Handout
List: A list is an ordered sequence which is mutable and made up of one or more elements. A list
can have elements of different data types, such as integer, float, string, tuple or even another list.
Elements of a list are enclosed in square brackets and are separated by comma.
Example of list:
1. L1 is the list of first five odd numbers 3. L3 is the list of mixed data types.
>>>L1=[1,3,5,7,9] >>>L3=[1,’school’,23.5,17.5,’college’]
>>>print(L1) >>>Print(L3)
[1,3,5,7,9] [1,’school’,23.5,17.5,’college’]
2. L2 is the list of vowels 4. L4 is the list of lists called nested list.
>>>L2=[‘a’,’e’,’i’,’o’,’u’] >>>L4=[[‘Aman’,34],[‘Sumith’,’30],[‘Ravi’,29]
>>>print(L2) ]
[‘a’,’e’,’i’,’o’,’u’] >>>>print(L4)
[[‘Aman’,34],[‘Sumith’,30],[‘Ravi’,29]]
Accessing elements in a list: The elements of a list are accessed using index number. For example,
>>>L1=[23,43,12,54,34,65]
Positive
0 1 2 3 4 5
Indexing
List
23 43 12 54 34 65
Elements
Negative
-6 -5 -4 -3 -2 -1
Indexing
>>>print(L1[2]) >>>print(L1[5]) >>>print(L1[1+3])
12 65 34
>>>print(L1[0]) >>>print(L1[-3]) >>>print(L1[9])
23 54 IndexError: list index out of range
Lists are mutable: It means that the content of list can be modified after it has been created. For
example,
>>>L1=[34,23,67,2,66] >>>L1[3]=22 # replacing 2 with 22
>>>print(L1) >>>print(L1)
[34,23,67,2,66] [34, 23, 67, 22, 66]
List Operations: the data type list allows manipulation of its contents through various operations
such as.
1. Concatenation: Python allows us to join two or more lists using concatenation operator (+)
for example.
>>>L1=[11,22,33,44,55]
>>>L2=[99,88,77]
>>>L1+L2
[11, 22, 33, 44, 55, 99, 88, 77]
>>>L3=['Red','Green','Blue']
>>>L4 =['Cyan', 'Magenta','Yellow','Black']
['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
NOTE: The content of L1, L2, L3, & L4 remains same after concatenation operation.
If we try to concatenate a list with elements of some other data type, TypeError occurs, For
example,
>>>L1=[1,2,3]
>>>L2=”Hello”
>>>L1+L2
TypeError: can only concatenate list (not "str") to list
2. Repetition: In Python, a list can be replicated by using replication operator (*). For example,
>>>L1=[11,22,33]
>>>L1*2
[11, 22, 33, 11, 22, 33] # Elements of List L1 is repeated twice
>>>L1=[‘Computer’]
>>>L1*3
[‘Computer’, ‘Computer’, ‘Computer’] # Elements of List L1 is repeated three times
3. Membership: In python, a list membership operator returns “True” if an element is present in
the list else return “False”. For example,
>>>L1=[‘a’,’b’,’c’,’d’]
>>>’a’ in L1 >>> 'f' in L1 >>> 'A' in L1
True False False
The ‘not in’ operator returns True if the element is not present in the list, else it returns false.
>>> 'A' not in L1 >>>'f' not in L1 >>>'a' not in L1
True True False
4. List Slicing: Slicing is used to extract a portion/slice of list item from the existing list. For
example
If L is a list, the expression L[start:Stop:Step] returns the portion of the list from index start to the
index stop, at a step size step.
>>>L1=[‘Anusha’, ’Deepika’, ’Harini’, ’Anvi’, ’Teju’, ’Shravani’, ‘Geetha’]
>>>L1[1:4]
['Deepika', 'Harini', 'Anvi']
>>>L1[2:5]
['Harini', 'Anvi', 'Teju']
>>>L1[3:9]
['Anvi', 'Teju', 'Shravani', 'Geetha'] # L1 will show all the elements till end as second index is out of
range.
>>>L1[3:1]
[] # First index is greater than Second index so it returns an empty list.
>>>L1[:3] # As first index is missing so starts from o
['Anusha', 'Deepika', 'Harini']
>>>L1[0:6:2] # Returns with step size of 2
['Anusha', 'Harini', 'Teju']
>>>L1[-6:-3] # Returns items from index -6 to -3(not included)
['Deepika', 'Harini', 'Anvi']
>>>L1[::2] # Returns complete list with step size 2 as start and stop index is missing.
['Anusha', 'Harini', 'Teju', 'Geetha']
5. Nested List: A list inside another list is called Nested List. For example,
>>>L1=[1,4,5,2,12,[7,8,9],11]
>>> print(L1)
[1, 4, 5, 2, 12, [7, 8, 9], 11]
>>>L1[5]
[7, 8, 9]
>>> L1[4]
12
To access the element of the nested list of L1, we have to specify two indices L1[m][n]. The first
index m will take us to the desired nested list and second index n will take us to the desired
element in that nested list. For example,
>>>L1[5][1] # Index 5 will return the 6th element of L1 which itself a list and index 1 return 2nd
element of that list which is 8.
Output: 8
6. Copying List: The simplest way to make a copy of the list is to assign it to another list. For
example,
>>>L1=[1,2,3]
>>>L2=L1
>>>L2
[1, 2, 3]
The statement L2=L1 does not create a new list. rather, it just makes L1 and L2 refer to the same
list object. It means that L2 actually becomes an alias of L1. So, any changes made to either of
them will be reflected in the other list. For example,
>>>L2[1]=6
>>>L1
[1,6,3]
We can also create a copy or clone of the list as a distinct object by three methods.
Method-1: We can slice our original list and store it into a new variable. For example,
>>>L1=[3,6,9]
>>>L2=L1[:]# Created using slicing notation
>>>L2
[3,6,9]
Here L2 and L1 are two distinct copies of list, changes done in L1 will not reflect in L2
Method-2: We can use the built in function list() to make distinct copy of a list. For example,
>>>L1=[3,6,9]
>>>L2=list(L1)
>>>L2
[3,6,9]
Method-3: We can also use copy() function to make a distinct copy of list. For example,
>>>import copy
>>>L1=[3,6,9]
>>>L2=[Link](L1)
>>>L2
[3,6,9]
7. Traversing a list: We can access each element of the list or traverse a list using a for loop or
while loop.
List traversal using for loop
Method-1 Method-2
>>>L1=[‘Mango’, ‘Banana’, ‘Guava’] >>>L1=[‘Mango’, ‘Banana’, ‘Guava’]
>>>for I in L1: >>>for I in range(len(L1)):
Print(I) print(L1[I])
Mango Mango
Banana Banana
Guava Guava
List Traversal using While loop
>>> L1=[‘Mango’, ‘Banana’, ‘Guava’, ’Orange’]
>>>i=0
>>>while i<len(L1):
Print(L1[i])
i=i+1
Mango
Banana
Guava
Orange
Methods of List (Built-in Functions)
1. append(): This function add a single element at the end of the list. For example,
>>>L=[34,45,56,23,12]
>>>[Link](77)
>>>print(L)
[34,45,56,23,12,77]
[Link](28,9) will return TypeError as append function can take only one argument.
This function can add a list at the end of another list. For example
>>>[Link]([28,29])
[34,45,56,23,12,77,[28,29]]
Program-1: Write a program to accept five numbers from the user and add in the given list.
L=[34,23,12]
Answer:
L=[34,23,12] Output:
k=0 Enter any number1
for i in range(5): Enter any number2
k=int(input("Enter any number")) Enter any number3
[Link](k) Enter any number4
print("List after appending is:",L) Enter any number5
List after appending is: [34, 23, 12, 1, 2, 3, 4, 5]
Program-2: Write a program to accept 10 numbers from the user and if the number is even then
add the elements in list l1 otherwise add in the list L2.
Answer:
L1=[] Output:
L2=[] Enter any number1
for i in range(10): Enter any number2
k=int(input("Enter any number")) Enter any number3
if k%2==0: Enter any number4
[Link](k) Enter any number5
else: Enter any number6
[Link](k) Enter any number7
print("Even Number List:",L1) Enter any number8
print("Odd Number List:",L2) Enter any number9
Enter any number10
Even Number List: [2, 4, 6, 8, 10]
Odd Number List: [1, 3, 5, 7, 9]
2. extend(): This function adds all the elements of one list at the end of the another list. For
example
>>>L1=[1,6,3,9]
>>>L2=[12,13,18,19]
>>>[Link](L2)
>>>print(L1)
[1,6,3,9,12,13,18,19]
All the elements of list L2 are added at the end of the list L1
Program-3: Write the output of the following programs.
>>>L1=[1,2,3] Output:
>>>L2=[7,8,9] [1,2,3,[7,8,9]]
>>>[Link](L2)
>>>print(L1)
>>>L1=[1,2,3] Output:
>>>L2=[7,8,9] [1,2,3,7,8,9]
>>>[Link](L2)
>>>print(L1)
3. insert(): This function helps us to add an element at a specific index value. For example
>>>L1=[23,12,45,32]
>>>[Link](3,77)
>>>print(L1)
[23,12,45,77,32]
4. reverse(): This function simply reverse the order of all the elements in the list. For example
>>>L1=[23,12,45,32]
>>>[Link]()
>>>print(L1)
[32,45,12,23]
Note: This function makes the changes in the original list. It does not create the new list.
5. len(): This function returns the length of list, for example
>>>L1=[12,34,43,23,78,90,1]
>>>print(len(L1))
7
6. Sort(): This function arrange all the elements in increasing order (by default). For example
>>>L1=[12,34,43,23,78,90,1]
>>>[Link]()
[1,12,23,24,43,78,90]
>>>L2=[“Sumit”, “Naman”, “Parth”, 76,90,”Mini”]
>>>[Link]()
TypeError: '<' not supported between instances of 'int' and 'str'
To arrange elements in decreasing/descending order.
>>>L1=[12,34,43,23,78,90,1] >>>L1=[12,34,43,23,78,90,1]
>>>[Link](reverse=True) >>>[Link]()
>>> print(L1) >>>[Link]()
[90, 78, 43, 34, 23, 12, 1] >>> print(L1)
[90, 78, 43, 34, 23, 12, 1]
7. count(): This function returns the frequency of an element in the list. In other words, we can
say that this function returns how many times an element has occurred in the list. For example
>>>L1=[1,2,5,2,6,1,7,9,1]
>>>print([Link](1))
3
>>>print([Link](2))
2
8. clear(): This function remove all the elements of the list. For example
>>>L1=[1,2,5,2,6,1,7,9,1]
>>>[Link]()
>>>print(L1)
[]
Deletion Operations
9. pop(): This function delete/remove the element from the specified index. This function also
return the deleted element. For example
>>>L1=[90, 56, 87, 98, 23, 6, 78]
>>>print([Link](3))
>>>print(L1)
98
[90,56,87,23,6,78]
Note: If we don’t give any index value in pop() function then it will delete the last element.
>>>L1=90,56,87,98,23,6,78]
>>>print([Link]())
>>>print(L1)
78
[90,56,87,98,23,6]
>>>L1[“Amit”, “Sumit”, “Naman”, “Manan”, “Kapil”]
>>>print([Link](-2))
>>>print(L1)
Manan
[‘Amit’, ‘Sumit’, ‘Naman’, ‘Kapil’]
10. del(): The del statement delete the element from the specified index. This statement does not
return the element. For example
>>>L1=[90,56,87,98,23,6,78]
>>>del L1[3]
>>>print(L1)
[90,56,87,23,6,78]
More than one element can be deleted by using del statement. For example
>>>L1=[90,56,87,23,6,78]
>>>del L1[2:5]
>>>print(L1)
[90,56,6,78]
11. remove(): This function delete the first occurrence of specified element. This function is used
when we know the element to be deleted but not the index value. For example
>>>L1=[90,56,87,98,23,6,78,98]
>>>[Link](98)
>>>print(L1)
[90,56,87, 23,6,78,98]
Program-4: Write a program to remove all even numbers from the list.
Answer:
L1=[90,56,87,98,23,6,78,98] Output:
L=len(L1) [87, 23]
i=0
while i<L:
if L1[i]%2==0:
del L1[i]
L=L-1
i=i-1
i=i+1
print(L1)
12. index(): This function simply returns the index value of specified element. For example
>>>L1=[90,56,87,98,23,6,78,98]
>>>print([Link](87))
3
If we specified an element which is not present in the list, then it will return an error. For example
>>>L1=[90,56,87,98,23,6,78,98]
>>>print([Link](77))
ValueError: 77 is not in list
13. max(): This function returns the largest value from the list. For example
>>>L1=[90,56,87,98,23,6,78,98]
>>>print([Link](L1))
98
>>>L1[“Amit”, “Sumit”, “Naman”, “Manan”, “Kapil”]
>>>print([Link](L1))
Sumit
14. min(): This function returns the smallest value from the list. For example
>>>L1=[90,56,87,98,23,6,78,98]
>>>print([Link](L1))
6
>>>L1[“Amit”, “Sumit”, “Naman”, “Manan”, “Kapil”]
>>>print([Link](L1))
Amit
Answer the following questions.
1. Write a program to accept five numbers from the user and store it in a list.
Answer:
L1=[] Enter any Number1
for I in range(5): Enter any Number2
n1=int(input(“Enter any Number”)) Enter any Number3
[Link](n1) Enter any Number4
print(L1) Enter any Number5
[1, 2, 3, 4, 5]
2. Write a program to accept names of five fruits from the user and store it in the list.
Answer:
L1=[] Enter Your Fav FruitBanana
for I in range(5): Enter Your Fav FruitApple
n1=input(“Enter Your Fav Fruit”) Enter Your Fav FruitMango
[Link](n1) Enter Your Fav FruitGrapes
print(L1) Enter Your Fav FruitKiwi
['Banana', 'Apple', 'Mango', 'Grapes', 'Kiwi']
3. Write a program to find the largest or smallest number from the given list.
L=[23,45,2,89,9,67,65,34,2].
Answer:
L=[23,45,2,89,9,67,65,34,2] 89
print(max(L)) 2
Print(min(L))
4. Write a program to find the largest and smallest number from the given list without using built-
in function(max() and min()). L=[23, 45, 22, 189, 94,67,65,34,12].
Answer:
L=[23,45,22,189,94,67,65,34,12] 189
max=l[0] 12
min=l[0]
for i in L:
if i>max:
max=i
else:
min=i
print(max)
print(min
5. Write a program to find the average of all the numbers stored in given list L=[5,10,15,20,25]
Answer:
L=[5,10,15,20,25] 15.0
Print(“average is:”, sum(L)/len(L))
6. Write a program to find the average of all the numbers stored in given list L=5,10,15,20,25]
without using inbuilt function (Sum() and Len())
Answer:
L=5,10,15,20,25] Average is : 15.0
Sum=0
Len=0
for I in L:
sum=sum+i
len=len+1
print(“Average is :”, sum/len)
7. Write a program to count the frequency of 1 in the given list. L=[1,2,3,4,2,3,4,1,2,3,1,4,3]
Answer:
L=[1,2,3,4,2,3,4,1,2,3,1,4,3] Frequency of 1 in list is: 3
print(“Frequency of 1 in list is:”, [Link](1))
8. Write a program to count the frequency of 1 in the given list. L=[1,2,3,4,2,3,4,1,2,3,1,4,3]
without using count() function.
Answer:
L=[1,2,3,4,2,3,4,1,2,3,1,4,3] Frequency of 1 in list is: 3s
count=0
for i in L:
if i==1:
count=count+1
print(“Frequency of 1 in list is:”, count)
9. Write a program to increase all the multiples of 5 in the given list by 1.
L=[23,2,45,65,112,20,35,3,70] for example
Original List= [23,2,45,65,12,20,35,3,70]
Modified List=[23,2,46,66,12,21,36,3,71]
L=[23,2,45,65,112,20,35,3,70] Original list is : [23, 2, 45, 65, 112, 20, 35, 3, 70]
print(“Original list is :”, L) Modified list is : [23, 2, 46, 66, 112, 21, 36, 3, 71]
for i in range(len(L)):
if L[i]%5==0:
L[i]=L[i]+1
print(“Modified list is :”,L)
10. Write a program to remove the largest element from the list L=[12,99,22,34,87,104,120,34,56]
Answer:
L=[12,99,22,34,87,104,120,34,56]
print(“Original List is :”, L)
[Link]([Link](max(L)))
Print(“Modified List is:”,L)
Exercise-1
1. Write the output of the following print statements.
L=[8,9,0,7,6,5,6,4,2]
print(L[3]) 7
print(L[5]) 5
print(L[-4]) 5
print(L[0]) 8
print(L[-0]) 8
print(L[2]**L[2]) 1
2. Write the output of the following print statements.
L=[23,34,12,65,43,25,36,89]
print(L[2:2]) []
print(L[3:7]) [65,43,25,36]
print(L[::-1]) [89,36,25,43,
print(L[-6:-1]) [12,65,43,25,36]
3. Write the output of the following:
L=[[23,34,12],[65,43,25],[36,89]]
print(L[2:2]) []
print(L[3:7]) []
print(L[::-1]) [[36, 89], [65, 43, 25], [23, 34, 12]]
print(L[-6:-1]) [[23, 34, 12], [65, 43, 25]]
4. Write the output of the following:
L=[[2,3,-1],[‘one’,’two’,’three’],[9]]
for i in L:
print(i)
Answer:
[2,3,-1]
[‘one’,’two’,’three’]
[9]
5. Write the output of the following:
L=[[2,3,-1],[‘one’,’two’,’three’],[9]]
for i in L:
print(i+i)
Answer:
[2, 3, -1, 2, 3, -1]
['one', 'two', 'three', 'one', 'two', 'three']
[9, 9]
6. Write the output of the following:
L=[[2,3,-1],[‘one’,’two’,’three’],[9]]
for i in L:
print(i[0]+i[0])
Answer:
4
oneone
18
7. Write the output of the following:
L=[[12,3,-1],[‘one’,’two’,’three’],[9]]
for i in L:
print([Link](‘four’))
print(L)
Answer: It is an infinite loop.
8. Write the output of the following code:
L=[[12,3,-1],[‘one’,’two’,’three’],[9]]
for i in range(3):
print([Link](‘four’))
print(L)
Answer:
None
[[12, 3, -1], ['one', 'two', 'three'], [9], 'four']
None
[[12, 3, -1], ['one', 'two', 'three'], [9], 'four', 'four']
None
[[12, 3, -1], ['one', 'two', 'three'], [9], 'four', 'four', 'four']
Multiple Choice Question
1. Which of the following statement will create list?
a. L1=list() b. L1=[1,2,3,4] c. Both of the above d. None of the above
2. Write the output of the code: list(“welcome”)
a. [‘w’,’e’,’i’,’c’,’o’,’m’,’e’] b. (‘w’,’e’,’i’,’c’,’o’,’m’,’e’)
c.[‘welcome’] d. None of the above
3. Write the output of the following code;
>>> L=[‘w’,’e’,’i’,’c’,’o’,’m’,’e’]
>>>print(len(L))
a. 7 b. 8 c. 9 d. None
4. Write the output of the following code:
>>>L=[“Amith”,”Anita”,”Zee”,”Longest Word”]
>>>print(max(L))
a. Zee b. Longest Word c. Error d. None of the above
5. Write the output of the following code:
>>>L=[“Amith”, ”Anita”, ”Zee”, ”Longest Word”,123]
>>>print(max(L))
a. Longest Word b. Zee c. Amit d. Error
6. Write the output of the following code:
>>>L=[1,5,9]
>>>print(sum(L),max(L),min(L))
a. 15 9 1 b. Error c. Max and Min are only for string value d. None
7. Do we have any inbuilt function for shuffling the values of List:
a. True b. False
8. Write the output of the following code:
>>> L=[1,2,3,4,5,[6,7,8]]
>>>print(L[5])
a. [6,7,8] b. 6,7,8 c. Error d. 6
9. Write the output of the following code:
print(L[20:-1])
a. [‘c’, ’o’] b. [‘c’, ’o’, ’m’] c. (com) d. Error
[Link] the output of the following code:
>>>L=list(“[Link]”)
>>>print(L[20:0])
a. Error b. No Value c. None d. []
11. Write the output of the following code:
>>>L=[‘Amit’, ‘Sumit’, ’Naina’]
>>>print(L[-1][-1])
a. [Naina] b. [a] c. a d. None of the above
12. Write the output of the following code:
>>> L=[‘Amit’, ‘Sumit’, ’Naina’]
>>>print(L[1:-1])
a. [‘Sumit’] b. [a] c. [Naina] d. None of the above
13. Write the output of the following code:
>>>L=[“Amith”, “Sumith”, “Naina”]
>>>print(L*2)
a. [‘Amith’, ‘Sumith’, ‘Naina’, ‘Amit’, ‘Sumit’, ‘Naina’]
b. [‘Amith’, ‘Sumith’, ‘Naina’]
c. Error
d. None of the above
14. Write the output of the following code:
>>>L=[“Amith”, “Sumith”, “Naina”]
>>>print(L**2)
a. Error
b. [‘Amith’, ‘Sumith’, ‘Naina’] [‘Amith’, ‘Sumith’, ‘Naina’]
c. [‘Amith’, ‘Sumith’, ‘Naina’]
d. [‘Amith’, ‘Sumith’, ‘Naina’, ‘Amith’, ‘Sumith’, ‘Naina’]
15. Write the output of the following output:
>>>L=[0.5* x for x in range(4)]
>>>print(L)
a. [0.0, 0.5, 1.0, 1.5] b. (0, 0.5, 1, 1.5) c. [0.0,0.5,1.0,1.5,2.0] d. Error
16. Write the output of the following code:
>>>L=[‘a’*x for x in range(4)]
>>>print(L)
a. [‘’,’a’,’aa’,’aaa’] b. [‘a’,’aa’,’aaa’] c. Error d. None of the above
17. Write the output of the following code:
>>>L=[1*x for x in range(10,1,-4)]
>>>print(L)
a. [10,6,2] b. [10,7,4] c. Error d. None of the above
18. Write the output of the following code:
L=[1,2,3,4,5]
for I in L:
print(I, end=’’)
i=I+1
a. 1 2 3 4 5 b. 1,3,5 c. Error d. None of the above
19. Write the output of the following Code:
>>>L=[‘Amit’, ’Sumit’, ’Naina’]
>>>L1=[“Sunil”]
>>>print(L+L1]
a. [‘Amit’, ‘Sumit’, ‘Naina’, [‘Sunil’]] b. [‘Amit’, ‘Sumit’, ‘Naina’, ‘Sunil’]
c. Liat cannot concatenate d. None of the above
20. Which command is used to add an element in List named L1.
a. [Link](4) b. [Link](4) c. [Link](4) d. None of the above
21. Write the output of the following:
>>>L=’123456’
>>>L=list(L)
>>>print(type(L[0]))
a. class ‘str b. class’int’ c. 1 d. Error
22. Write the output of the following:
>>>T=(1,2,3,4,5.5)
>>>L=list(T)
>>>print(L[3]*2.5)
a. Error b. 10 c. 10.0 d. 4
23. Index value in list and string start from 0 (True or False)
Answer: True
24. Write the output of the following:
>>>T=(1,2,3,4,5.5)
>>>L=list(T)
>>>print(L*2)
a. [2,4,6,8,11] b. [1,2,3,4,5.5,1,2,3,4,5.5] c. Error d. None
25. Write the output of the following:
>>>T=[1,2,3,4]
>>>T1=[3,4,5,6]
>>>T2=T+T1
print(T2)
a. [1,2,3,4,5,6] b. [1,2,3,4,3,4,5,6] c. [4,6,8,10] d. Error
26. Write the output of the following:
>>>T=[1,2,3,4]
>>>T1=[3,4,5,6]
>>>T2=[Link](T1)
>>>print(T2)
a. [1,2,3,4,[3,4,5,6]] b. [1,2,3,4,3,4,5,6]
c.[[3,4,5,6],[1,2,3,4] d. None of the above
27. del statement can delete the following from the list?
a. Single Element d. Multiple Element
c. All element along with list object d. All of the above
28. Write the output of the following:
>>>T[1,2,3,4]
>>>T1=T
>>>T[0]=”A”
>>>print(T)
>>>print(T1)
a. [‘A’,2,3,4] b. [‘A’,2,3,4] c. [1,2,3,4] d. Error
[1,2,3,4] [‘A’,2,3,4] [1,2,3,4]
29. What type of error is returned by the following statement?
>>>T=[1,2,3,4]
>>>print([Link](9))
a. IndexError b. TypeError c. ValueError d. None of the above
30. Write the output of the following:
>>>L=[“Amit”, “Sumit”, “Naina”]
>>>L1=[:Sumit”]
>>>print(L-L1)
a. [“Amit”, “Naina”] b. [“Amit”, “Naina”, “Sumit”] c. Show Error d. None
31. Which of the following is not list operator?
a. Indexing b. Slicing c. Dividing d. Concatenation
32. Which of the following is true about List data type in Python?
a. List is a sequence data type b. List is mutable
c. List can have elements of different data type d. All of the above
33. Identify data type of ‘T’ in following line of code:
>>>T=list(tuple([1,2,3]))
>>>print(type(T))
a. Tuple b. List c. Nested List d. None of the above
34. List and String are different
a. in reference to their indexing
b. in reference to data type of elements they contain
c. Both a & b
d. None of the above
35. If we try concatenate a list with elements of some other data type, _________ occurs.
a. SynataxError b. IndentationError c. TypeError d. None
36. Name the operator which is used in the following print statement.
>>>L1=[1,2,3]
>>>print(L1*3)
a. Concatenation b. Repetition c. Membership d. None
37. State weather the following statement is true or false
print(L1+L1) and print(L1*2) will produce the same result. (L1is a List).
Answer: True
38. remove() function removes the ______________ occurrences of an element from the list.
a. all b. first c. last d. None of the above
39. Write the output of the following.
>>>L=[“Amit”, “Sumit”, “Ravi”]
>>>print(“@”.join(L))
a. @Amit b. Amit@Sumith@Ravi
c. Amit@Sumith@Ravi@ d. None of the above
40. Write the output of the following:
L1=[‘C++’, ‘C-Sharp’, ‘Visual Basic’]
L2=[[Link]() for name in L1]
L3=[name for name in L1]
if (L2[2][0]==L3[2][0]):
print(“Yes”)
else:
print(“No”)
a. No b. Yes c. Error d. None of the above
Chapter-7
Tuples in Python
Tuples: A tuple is an ordered sequence of elements of different data types, such as integer, float,
string or list. Elements of a tuple are enclosed in parenthesis (Round/open Brackets) and are
separated by commas. For example,
>>> a= (1,’2’,7,6.5,’a’) # a is a tuple of mixed data type
>>>b= (2,4,6,8,10) # b is a tuple of only integers
>>>c= (‘a’, ’b’, ’c’, ’d’) # c is a tuple of only strings
>>>d= (2,4,7, [4,5,6]) # d is a tuple with list as an element

If there is a single element in a tuple then the element should be followed by a comma, otherwise
it will be treated as integer instead of tuple. For example
>>> a=(2) >>> b=(2,)
>>> type(a) >>> type(b)
<class 'int'> <class 'tuple'>

>>> c=('a') >>> d=('a',)


>>> type(c) >>> type(d)
<class 'str'> <class 'tuple'>

Note: A sequence without parentheses is treated as tuple by default


>>> a=1,2,3,4
>>> type(a)
<class 'tuple'>

Accessing Elements in a Tuple: Elements of a tuple can be accessed in the same way as a list
or string using indexing and slicing. For example
>>>a=(‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’)
Positive 0 1 2 3 4 5 6 7
Indexing
Elements C O M P U T E R
Negative -8 -7 -6 -5 -4 -3 -2 -1
Indexing

>>> a[4] # This is accessing the element at index 4.


'u'
>>> a(4) # This is trying to call the tuple 'a' as a function.
TypeError: 'tuple' object is not callable

Tuple is immutable:
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it
has been created. For example:
a=('c', 'o', 'm', 'p', 'u', 't', 'e', 'r')
>>> a[2]='s'
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a[2]='s'
TypeError: 'tuple' object does not support item assignment

Difference between List and Tuple


LIST TUPLE
It is mutable data type It is an immutable data type
Elements are enclosed in square brackets i.e [] Elements are enclosed in parenthesis i.e ()
Iterating through a list is slower as compared Iterating through a tuple is faster as compared
to a tuple to a list.

Tuple Operations:
1. Concatenation: Joining of two or more tuples is called concatenation. Python allows us to join
tuples using concatenation operator (+)
Example:
>>>t1=(1,2,3)
>>>t2=(8,9,10)
>>>t1+t2
Output:
(1,2,3,8,9,10)
2. Repetition (*): It is used to repeat elements of a tuple.
>>>h1=(‘H’, ‘M’)
>>>h1*3
Output:
('H', 'M', 'H', 'M', 'H', 'M')
3. Membership: The ‘in’ operator checks the presence of element in tuple. If the element is
present, it returns True, else it returns False.
The not in operator returns True if the element is not present in the tuple, else it returns False.
Example:
>>>h1=(‘H’, ‘M’)
>>>’H’ in h1
Output:
True
>>>’m’ not in h1
True
4. Slicing: It is used to extract one or more elements from the tuple. Like string and list, slicing
can be applied to tuples also.
Example:
>>>t1=(1,2,3,7,8,9)
>>>t1[2:4]
(3,7)
>>>t2=(10,20,30,40,50,60,70,80)
>>>t1[2:7]
(30,40,50,60,70)
>>>t1[:5]
(10,20,30,40,50)
>>>t1[::-1]
(80,70,60,50,40,30,20,10)

Built-in Function:

1. len(): This method returns the length of tuple or the number of elements in the tuple.
>>>t1=(10,20,30,40,50,60,70,80)
>>>len(t1)
8
2. tuple(): This function creates an empty tuple or creates a tuple if a sequence is passed as
argument.
>>>t1=tuple()
>>>type(t1)
Output: <class 'tuple'>
>>>t2=tuple(‘python’)
>>> type(t2)
<class 'tuple'>
>>>t3=('p', 'y', 't', 'h', 'o', 'n')
>>>t3=tuple([1,2,3])
>>>t3
(1,2,3)
>>>t4=tuple(range(7))
>>>t4
(0,1,2,3,4,5,6)
3. count(): This function returns the frequency of an element in the tuple.
>>>t1=tuple(“tuple in python”)
>>>[Link](‘p’)
2
4. index(): This function returns the index of the first occurrence of the element in the given
tuple.
>>>t1=tuple(“tuples in python”)
>>>[Link](‘n’)
8
>>>t1=tuple(“tuples in python”)
>>>[Link](‘f’)
Output: ValueError: [Link](x): x not in tuple
5. sorted(): This element takes tuple as an argument and return a sorted list. This function does
not make any change in the original tuple.
>>>t1=(‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>sorted(t1)
Output: [‘e’, ‘l’, ‘p’, ‘s’, ‘t’, ‘u’]
6. min(): This function returns minimum or smallest element of the tuple.
>>>t1=(3,8,4,10,1)
>>>min(t1)
1
7. max(): This function returns maximum or largest element of the tuple.
>>>t1=(3,8,4,10,1)
>>>max(t1)
10
>>>t1=(‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>max(t1)
U
8. sum(): This function returns sum of the elements of the tuple.
>>>t1=(3,8,4,10,1)
>>>sum(t1)
26
Tuple Assignment: It allows a tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on the right side. The number of variables on the left should
be same as the number of elements in the tuple. For example,
>>>(n1,n2)=(5,9)
>>>print(n1)
5
>>>print(n2)
9
>>>(a,b,c,d)=(5,6,8)
ValueError: not enough values to unpack (expected 4, got 3)

Nested Tuple: A tuple inside another tuple is called a nested tuple. In nested tuple we can access
the elements in the same way of nested list. For example,
>>>t1=((“Amit”, 90), (“Sumith”, 75), (“Ravi”, 80))
>>>t1[0]
(“Amit”, 90)
>>>t1[1][1]
75

Answer the following questions:


1. What do you mean by tuple in python?
Answer: A tuple is an ordered sequence of elements of different data types, such as integer, float,
string, list or even a tuple. Elements of a tuple are enclosed in parenthesis and are separated by
commas.
2. Write a statement to create an empty tuple named ‘T1’.
Answer: T1=() or T1=tuple()
3. Write a statement to create a tuple ‘T1’ Containing first five even numbers.
Answer: T1=(2,4,6,8,10)
4. Write the code to convert the given list L1 to tuple. L1=[1,2,3,4,5]
Answer: T1=tuple(L1)
5. Write a statement to create tuple T1 with single element.
Answer: T1=(4,)
6. Write the output of the following code:
T1=(4)
Print(type(T1))
Answer: <class ‘int’>
7. Write the output of the following code:
T1=4,5,6
Print(type(T1))
Answer: <class ‘tuple’>
8. Write the output of the following code.
T1=(1,2,3,4,5,6,7,8)
print(T1)
print(T1*2)
print(T1+T1)
print(len(T1)*2)
Answer: (1,2,3,4,5,6,7,8)
(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8)
(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8)
16
9. Write a statement to create tuple T1 with the following data.
1, 4, ‘cs’, ‘ip, 5
Answer: T1=(1, 4, ‘cs’, ‘ip, 5)
10. Write the output for the following code:
T1=(1,2,3,4,5,6,7,8)
print(T1[0])
print(T1[-1])
print(T1[2+3])
print(T1[4-1])
print(T1[7%2])
Answer:
1
8
6
4
2
11. Write the output of the following:
T1=(1,2,3,4,5,6,7,8)
print(T1[:])
print(T1[3:])
print(T1[:4])
print(T1[-2:-5])
Answer:
(1,2,3,4,5,6,7,8)
(4,5,6,7,8)
(1,2,3,4)
()
12. Write the output of the following:
T1=(1,2,3,4,5,6,7,8)
print(T1[1::2])
print(T1[-1:-5:-2])
print(T1[::-1])
print(T1[:7:2])
Answer:
(2,4,6,8)
(8,6)
(8,7,6,5,4,3,2,1)
(1,3,5,7)
13. Which error is returned by the following code:
T1=(1,2,3,4,5,6,7,8)
print(T1[15])
Answer: IndexError: tuple index out of range
14. Write two differences between Tuple and List.
Answer:
Tuple List
It is immutable data type It is mutable data type
Iteration is faster through Tuple Iteration is slower in List
Tuple uses less memory List uses more memory
15. Write a statement in python to concatenate the given tuples.
T1=(1,2,3)
T2=(5,6,7)
Answer:>>> T1+T2
16. Write the output of the following code:
T1=(45,67,98)
T1=T1+(1,2,3)
Print(T1)
Answer: (45,67,98,1,2,3)
17. Write the output of the following code:
T1=(45,67,98)
T1=T1*3
print(T1)
Answer: (45,67,98, 45,67,98, 45,67,98)
18. Write the output of the following code:
T1=(45,67,98)
T2=((45,67,98))
print(T1 in T2)
print(45 in T2)
print(45 in T1)
print(T1+T2)
Answer:
False
True
True
(45,67,98,45,67,98)
19. Explain the following functions in reference to Tuple in Python.
a. len() b. Count()
Answer:
len() count()
This function returns the number of elements of This function returns the number of times the
the tuple. given element appears in the tuple.
Example: Example:
>>>t1=(10,20,30,40,50) >>>t1=(10,20,30,10,40,10,50)
>>>len(t1) >>>[Link](10)
5 3
20. Write a program to accept five numbers from the user and store it in the tuple ‘T1’.
Answer:
T1=() Enter any Number:1
i=0 Enter any Number:2
while(i<5): Enter any Number:3
num=int(input("Enter any Number:")) Enter any Number:4
T1=T1+(num,) Enter any Number:5
i=i+1 (1, 2, 3, 4, 5)
print(T1)
21. Write a program to accept five fruit names from the user and store it in a tuple ‘F1’.
Answer:
F1=() Enter any fruit name:Apple
i=0 Enter any fruit name:Banana
while(i<5): Enter any fruit name:Kiwi
Fruit=input("Enter any fruit name:") Enter any fruit name:Peach
F1=F1+(Fruit,) Enter any fruit name:Strawberry
i=i+1 ('Apple', 'Banana', 'Kiwi', 'Peach', 'Strawberry')
print(F1)
22. Write a program to store ‘n’ number of sports in a tuple ‘s1’. (Accept ‘n’ from the
user)
Answer:
s1=() How many sports you want to enter:2
n=int(input("How many sports you want to Enter Sport name:Hockey
enter:")) Enter Sport name:Cricket
i=0 ('Hockey', 'Cricket')
while(i<n):
sport=input("Enter Sport name:")
s1=s1+(sport,)
i=i+1
print(s1)
23. Consider the following tuple and write the code for the following statements:
T1=(12,3,45, ‘Hockey’, ‘Anil’, (‘a’, ‘b’))
a. Display the first element of T1
b. Display the last element of T1
c. Display T1 in reverse order.
d. Display ‘Anil’ from tuple T1
e. Display ‘b’ from tuple T1
Answer:
a. print(T1[0])
b. print(T1[-1])
c. print(T1[::-1])
d. print(T1[4]) or print(T1[-2])
e. print(T1[-1][-1]) or print(T1[5][1])
24. Write the output of the following:
for i in tuple(“SHIMLA”):
print(i+i)
Answer:
SS
HH
II
MM
LL
AA
25. Write the output of the following:
>>>7 in tuple(“123456789”)
>>> ‘7’ in tuple(“123456789”)
Answer:
False
True
26. Write the output of the following:
T1=(23,32,4,5,2,12,23,7,9,10,23)
print(len(T1)+T1[-1])
print(T1[[Link](23)+len(T1)-5])
print([Link](T1[6]))
print([Link](max(T1)))
Answer:
34
10
3
1
27. Write the output of the following:
T1=(23,32,4,5,2,12,23,7,9,10,23)
Print(max(T1))
Print(min(T1))
Answer: 23
2
28. Write the output of the following:
T1=(‘Hockey’, ‘Cricket’, ‘Football’)
print(max(T1))
print(min(T1))
Answer:
Hockey
Cricket
29. Write the output of the following:
T1=(‘Raman’, ‘Ram’, ‘Ramaiya’)
print(max(T1))
print(min(T1))
Answer:
Raman
Ram
30. Write the output of the following:
T1=(23,32,4,5,2,12,23,7,9,10,23)
print(sorted(T1))
print(sorted(T1[2:7]))
print([Link](23))
print([Link](23,3,9))
Answer:
[2,4,5,7,9,10,12,23,23,32]
[2,4,5,12,23]
0
6
31. Write the output of the following:
T1=(23,32,4,5,2,12,23,7,9,10,23)
print(sum(max(T1)+min(T1)))
Answer:
TypeError: 'int' object is not iterable
32. Write a program to accept three numbers from the user and insert it at the end of
given Tuple T1.
T1=(23,32,4,5,2,12,23,7,9,23)
Answer:
T1=(23,32,4,5,2,12,23,7,9,10,23) Enter any Number: 10
t=() Enter any Number: 11
for i in range(3): Enter any Number: 12
n1=int(input("Enter any Number: ")) (23, 32, 4, 5, 2, 12, 23, 7, 9, 10, 23, 10, 11, 12)
t=t+(n1,)
T1=T1+t
print(T1)
33. What type of error is returned by following statement:
>>>(a,b,c,d)=(5,6,8)
Answer: ValueError: not enough values to unpack (expected 4, got 3)
34. Write the output of the following code:
>>>(name,rollno,subject)=(“Anil”,9,”CS”)
>>>name
Answer: Anil
35. Which escape character is used for the following:
a. for adding horizontal tab space
b. for inserting a new line
Answer:
a. \t b. \n
36. What do you mean by Nested Tuple? Give one example.
Answer: A tuple inside another tuple is called a nested tuple. For example:
St=((101, “Amit”,90), (107, “Anish”,85), (21, “Suman”, 80))
37. Write a statement to print 30 from the given tuple.
A=(“Seventy”, [1,2,3], (20,30,40), “Eighty”)
Answer: print(a[2][1])
38. Write a statement to unpack the following tuple into 3 variables.
(60,70,80)
Answer: (n1,n2,n3)=(60,70,80)
39. Write a program to swap the values of given tuples.
T1=(“A”, “B”)
T2=(34,65)
Answer:
T1=(“A”, “B”) T1= (34, 65)
T2=(34,65) T2= ('A', 'B')
T1,T2=T2,T1
print(“T1=”, T1)
print(“T2=”, T2)
40. Write the output of the following code:
T1=(“A”, [“B”,”D”],”C”)
T1[1][1]=”C”
print(T1)
Answer: (‘A’, [‘B’, ‘C’], ‘C’]
41. Write a program to print the frequency of a number accepted from the user in given
tuple: T1=(12,17,18,25,19,12,18,5).
Answer:
T1=(12,17,18,25,19,12,18,5) Enter any Number:12
n1=int(input(“Enter any Number”)) 2
print([Link](n1)) Enter any Number13
0
42. Write a program in python to concatenate all the characters of given tuple. T1=(‘B’,
‘O’, ‘O’, ‘K’)
Note: Expected Output: BOOK
Answer:
Method-1 Method-2
T1=(‘B’, ‘O’, ‘O’, ‘K’) T1=(‘B’, ‘O’, ‘O’, ‘K’)
St= “” St= “”.join(T1)
for i in T1: print(st)
st=st+i
print(st)

43. Write a program to remove a number (accepted from the user) from the given tuple
T1=(12,15,18,21,24,27,30)
Note: Sample Execution
Enter element to remove:21
Tiple after removing element is: (12,15,18,24,27,30)
T1=(12,15,18,21,24,27,30) enter the number to be removed:30
el=int(input("enter the number to be (12, 15, 18, 21, 24, 27)
removed:"))
if el in T1:
L=list(T1)
[Link](el)
T1=tuple(L)
print(T1)
else:
print("Element not found")
44. What do you mean by Unpacking Tuple? Give Example.
Answer: Creating/Initializing individual variables from the values of tuple is called unpacking.
For example,
T1=(2,4,6)
X,y,z=T1
print(x)
print(y)
print(z)
Output:
2
4
6
45. What do you mean by Packing Tuple? Give Example
Answer: Creating a tuple from individual values is called packing tuple. For example,
T1=2,4,6
46. Write one similarity between Tuples and String.
Answer: Tuples and Strings are immutable; means we cannot edit values in a Tuple and String.
47. Write the output of the following:
>>>T1=(2,’Apple’,6)
>>>print(max(T1))
Answer: TypeError: '>' not supported between instances of 'str' and 'int'
48. Consider the given tuple and write the output of given statements: T1=(1,23,4,5,
“A”,[“C”, “D”],(23,45), 45)
[Link](len(T1))
2. print([Link](45))
3. print([Link](45))
4. print(T1[5][0]*2)
5. print(T1[:])
6. print(T1[5:])
7. Print([Link](“A”))
8. print(T1[-1:-7:-2])
9. print(T1[4]+T1[5])
10. print(max(T1))
Chapter-8
Dictionary in Python
Dictionary: A python dictionary is a collection of elements where each element is a combination
of Key-Value pair. Each value/s is associated with a unique key. All the Key-Value pairs are
enclosed in curly braces. In other words, we can say that “Dictionaries are mutable, unordered
collection of elements in the form of Key-Value pairs which are enclosed in curly braces”.
Note: In Python 3.5 and before, iterating over a dict would return keys in arbitrary order. The order
of iteration would not match the order in which the items were inserted. Starting with python 3.6
and above versions, dictionaries will preserve insertion order.
Example:
1. A={1: “one”, 2: “Two”, 3: “Three”}
2. B={“A”: “Apple”, “B”: “Ball”, “C”: “Cat”}
3. B={"A": "Apple", "B": "Ball", "B": "Cat"}
>>>B
{'A': 'Apple', 'B': 'Cat'}

Dictionary A has numeric Keys (1,2,3) and Values (“One”, “Two”, “Three”) are in string, while
dictionary B has both keys(‘A’, ‘B’, ‘C’) and Values (“Apple”, “Ball”, “Cat”) are in string.

Characteristics of Python Dictionary:


1. The combination of Key and Value is called Key-Value pair.
2. Keys and its values are separated by colon (:).
3. Different Key-Value pairs are separated by comma (,).
4. Keys are unique for each value.
5. Keys of dictionary must be of immutable type like string, number etc.
Method to create Empty Dictionary: There are two ways to create an empty dictionary which
are as follows
1. A={ } # A is an empty dictionary.
2. A=dict() # dict() method will create an empty dictionary.
3. Specify Key: Value pairs as keyword arguments to dict() function, keys as arguments
and values as their values.
>>>Employee=dict(name= ‘Amit’, salary=10000, age=24)
>>> Employee
{'name': 'Amit', 'salary': 10000, 'age': 24}
4. Specify comma-separated key:value pairs: To givr key:value pairs in the following format.
>>> Employee=dict({'name':'Amit', 'salary':10000, 'age':24})
>>> Employee
{'name': 'Amit', 'salary': 10000, 'age': 24}
5. Specify keys separately and corresponding values separately. In this method, the keys
and values are enclosed separately in parentheses and are given as arguments to the ‘zip()’
function, which is then given as argument of dict().
>>> employee=dict(zip(('name','salary','age'),('Amit',10000,25)))
>>> employee
{'name': 'Amit', 'salary': 10000, 'age': 25}
Zip(): The zip function clubs first value from set with first value with second set, and so on
6. Specify key: value pairs separately in form of sequences. In this method, one list or tuple
argument is passed to dict(). This argument contains list/tuples of individual key:value pairs.
>>> employee=dict([['name','Amit'],['Salary','10000'],['age',24]])
>>> employee
{'name': 'Amit', 'Salary': '10000', 'age': 24}
>>> employee=dict((('name','Amit'),('Salary','10000'),('age',24)))
>>> employee
{'name': 'Amit', 'Salary': '10000', 'age': 24}
Method to create Dictionary at run time:
Q1. Write a program to enter roll number and names of five students stored the data in
dictionary.
d={} Enter Roll Number: 1
for i in range(5): Enter your Name: Amit
rno=int(input("Enter Roll Number: ")) Enter Roll Number: 2
name=input("Enter your Name: ") Enter your Name: Sumit
d[rno]=name Enter Roll Number: 3
print(d) Enter your Name: Amit Reddy
Enter Roll Number: 4
Enter your Name: Sumit Reddy
Enter Roll Number: 5
Enter your Name: P Reddy
{1: 'Amit', 2: 'Sumit', 3: 'Amit Reddy', 4: 'Sumit
Reddy', 5: 'P Reddy'}
Note: d[rno]=name: Assigns the name entered by the user to the roll number entered by
the user in the dictionary d.

Q2: Write a program to store book id, book name and price of three books and store the
data in dictionary named “dict”.
dict={} Enter Book ID: 1
for i in range(3): Enter Book Name: Python
b_id=int(input("Enter Book ID: ")) Enter Book Price: 499
b_name=(input("Enter Book Name: ")) Enter Book ID: 2
b_price=int(input("Enter Book Price: ")) Enter Book Name: Java
temp=[b_name,b_price] #temporary list Enter Book Price: 399
dict[b_id]=temp Enter Book ID: 3
print(dict) Enter Book Name: AI with Python
Enter Book Price: 589
{1: ['Python', 499], 2: ['Java', 399], 3: ['AI with
Python', 589]}
Adding Elements to Dictionary: you can add new elements (key:value pair) to a dictionary
using assignment as per the following syntax. But the key added must not exist in dictionary and
must be unique. If the key is already exists, then this statement will change the value of existing
key and no new entry will be added to dictionary.
Syntax: <dictionary>[<key>]=<value>
Example:
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> B['8']='Harini'
>>> B
{1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi', '8': 'Harini'}

Updating/Modifying Existing Elements in a Dictionary: you can change the value of an


existing key using assignment as per the following syntax.
Syntax: <dictionary>[<key>]=<value>
Example:
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> B
{1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi', '5': 'Harini'}
>>> B[5]='Harini'
>>> B
{1: 'Amit', 2: 'Sunil', 5: 'Harini', 6: 'Suman', 7: 'Ravi', '5': 'Harini'}
>>>

Appending value in Python Dictionary: We can add new element in dictionary by the
following way.
Example:
A={1: 'one', 2: 'Two', 3: 'Three'}
A[4]= “Four”
print(A)
Output:
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

Example:
A={1: 'one', 2: 'Two', 3: 'Three'}
B={“A”: “Apple”, “B”: “Ball”, “C”: “Cat”}
[Link](B)
print(A)
Output:
{1: 'one', 2: 'Two', 3: 'Three', 'A': 'Apple', 'B': 'Ball', 'C': 'Cat'}
Note: It over writes the values of same keys and add the values of different keys.

Example:
A={1: 'one', 2: 'Two', 3: 'Three'}
B={1: 'Four', 2: 'Five', 3: 'Six', 4: 'Seven'}
[Link](B)
print(A)
Output:
{1: 'Four', 2: 'Five', 3: 'Six', 4: 'Seven'}

Update values in a python Dictionary: We cannot change the key of an element, but can
change the value of a respective key as follows.
Example:
B A={'A': 'Apple', 'B': 'Ball', 'C': 'Cat'}
A['B’] = 'Banana'
print(A)
Output:
{'A': 'Apple', 'B': 'Banana', 'C': 'Cat'}

Removing an element from a dictionary: There are two ways by which we can delete the
elements of dictionary.

1. By using del statement:


Syntax: del<Dictionary-name> [key of element]
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> del B[2]
>>> B
{1: 'Amit', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> del B[3]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
del B[3]
KeyError: 3

2. By using pop() function: This function not only delete the element of required key but also
return the deleted value.
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> a=[Link](2)
>>> print(a)
>>> print(B)
Sunil
{1: 'Amit', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}

Checking for Existence of a key: Usual membership operators ‘in’ and ‘not in’ work with
dictionaries as well. But they can check for the existence of keys only.
To use a membership operator for a key’s presence in a dictionary, you may write statement as
per syntax given below:

<key> <membership operator> <dictionary>


Example:
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> B
{1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> 1 in B
True
>>> 10 in B
False
>>> 'Ravi' in B
False
>>> 10 not in B
True
However, if you need to search for a value in a dictionary, then you can use the in operator with
Syntax: <‘value’> <membership operator><dictionary>.values()
Example:
>>> 'Ravi' in [Link]()
True
>>> 'Harini' not in [Link]()
True

Pretty Printing a Dictionary: To pretty print a dictionary in Python, you can use the ‘json’
module, which stands for " JavaScript Object Notation." This will display the dictionary with a nicer
formatting, especially useful when dealing with nested dictionaries or dictionaries with long values.
Alternatively, you can also use [Link]() with indent parameter to achieve pretty printing.

[Link](): The main purpose of [Link]() is to serialize Python objects into a JSON
formatted string. This means converting a Python object (such as a dictionary or a list) into a string
representation in the JSON format.

Example:
B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
import json
print([Link](B, indent=2))
Output:
{
"1": "Amit",
"2": "Sunil",
"5": "Lata",
"6": "Suman",
"7": "Ravi"
}

Counting Frequency of elements in a list using dictionary:

Split(): the split() function is a built-in method used to split a string into a list of substrings based
on a specified delimiter.
Syntax: [Link](separator)
separator (optional): The delimiter string based on which the splitting is performed. If not
provided, the default delimiter is whitespace (space, tab, newline).

Example:1
>>> text = "Hello world! This is a sentence."
>>> words = [Link]()
>>> print(words)
['Hello', 'world!', 'This', 'is', 'a', 'sentence.']
Example:2
>>> text="One, Two Three, Four, Five"
>>> word=[Link](',')
>>> print(word)
['One', ' Two Three', ' Four', ' Five']

Program to count the frequency of a list of elements using a dictionary.


import json Counting Frequencies in list
sentence="This is a super idea This\ : ['This', 'is', 'a', 'super', 'idea', 'This', 'idea', 'will',
idea will change the idea of learning" 'change', 'the', 'idea', 'of', 'learning']
words=[Link]() {
d={} "This": 2,
for one in words: "is": 1,
key=one "a": 1,
if key not in d: "super": 1,
count=[Link](key) "idea": 3,
d[key]=count "will": 1,
print("Counting Frequencies in list \n:", words) "change": 1,
print([Link](d,indent=1)) "the": 1,
"of": 1,
"learning": 1
}

Dictionary Functions and methods:


1. The len() Function: To get the length of the dictionary, i.e, the count of the key:value pair, you
can use the len() function.
Syntax: len(<Dictionary>)
Example:
>>> B={1: 'Amit', 2: 'Sunil', 5: 'Lata', 6: 'Suman', 7: 'Ravi'}
>>> len(B)
5
>>>B['8']='Harini'
>>> len(B)
6

Accessing Items, Keys and Values: get(), items(), keys(), values() methods can access
individual, values, all items, keys and values of the dictionary using the following methods.
<dict>.get() # to get values of the given key
<dict>.items() # to get all the items of the dictionary
<dict>.keys() # to get all the keys of the dictionary
<dict>.values # to get all the values of the dictionary
The get() method: It is used to get the value of the given key. It accepts two parameters. The
first is key and the second is default arguments. The default argument contains an error message
if the key is not present in the dictionary.
>>> d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
>>> print([Link]('Virat'))
45
>>> print([Link]('Sachin','Not Found'))
Not Found
>>> print([Link]('Sachin'))
None

items(): It is used to get the items presents in the dictionary as a sequence of (key, value) tuples.
d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}
l=[Link]()
for i in d:
print(i)
Output:
Virat
Rehane
Pujara
Rahul

keys(): This method returns all the keys of a dictionary in a list form. It will not follow any
particular order. Observe this example:
d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
print([Link]())
Output:
dict_keys(['Ramesh', 'Suresh', 'Akhilesh', 'Sameer'])

values(): It will return values in list form from the dictionary. Just take a look at this:
d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
print([Link]())
Output:
dict_values([15000, 20000, 21000, 22000])

Creating Dictionary from keys- the fromkeys() method: The fromkeys() method is used to
create a new dictionary from a sequence containing all the keys and a common value, which will
be assigned to all the keys.
Syntax: [Link](<key sequence>, [<value>])
Where the method name is to be used as [Link] and:
<key sequence> is a python sequence containing the keys for the new dictionary.
<value> is the common value that will be assigned to all the keys; if skipped, value None is
assigned to all the keys.
Example:
>>> A=[Link]([2,4,6,8],100)
>>> A
{2: 100, 4: 100, 6: 100, 8: 100}
>>> A=[Link]([2,4,6,8])
>>> A
{2: None, 4: None, 6: None, 8: None}
>>> A=[Link](3)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
A=[Link](3)
TypeError: 'int' object is not iterable
>>> A=[Link](3,)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
A=[Link](3,)
TypeError: 'int' object is not iterable
>>> A=[Link]((3,))
>>> A
{3: None}
>>> A=[Link]([3])
>>> A
{3: None}
Extend/Update Dictionary with new key:value pairs: update() and setdefault()
methods.

We can extend or update a dictionary by adding or updating a single key:value pair to an existing
dictionary or we can add/update key:value pairs from another dictionary, using the following
methods.

<dict>.setdefault() to insert a new key:value pair

<dict>.update() to update or add key:value pairs from a dictionary

1. The setdefault() method: The setdefault() method inserts a new key:value pair ONLY IF the
key doesn’t already exist. If the key already exists, it returns the current value of the key. You can
use this method as: [Link](<key>,<value>)

Where <key> and <value> are the key and value to be added to the dictionary, if <value> is not
passed as input, the default none value is used as the value.

This method works in two ways.

1. If the given key is NOT ALREADY PRESENT in the dictionary, it will add the specified
new key:value pair to the dictionary and return the value of the added key.

2. If the key is ALREADY PRESENT in the dictionary, the dictionary will not be updated, but
the current value associated to the specified key is returned.

>>> marks={1:350, 2:423, 3:411, 4:300}

>>> [Link](5,320)

320

>>> marks

{1: 350, 2: 423, 3: 411, 4: 300, 5: 320}

>>> [Link](5,340)

320

>>> marks
{1: 350, 2: 423, 3: 411, 4: 300, 5: 320}

Note: If we only provide a key without any value and the key does not exist in the dictionary, it
will take none as the value.

>>> [Link](6)

>>> marks

{1: 350, 2: 423, 3: 411, 4: 300, 5: 320, 6: None}

2. The update() method: This method merges key:value pairs from the new dictionary into the
original dictionary, adding or replacing as needed. The items in the new dictionary are added to
the old one and override any items already there with the same keys.

Example:

>>> Employee1={'name':'Krishna Geetha', 'salary':10000, 'age':25}

>>> Employee2={'name':'Diya', 'salary':540000, 'dept':'Sales'}

>>> [Link](Employee2)

>>> Employee1

{'name': 'Diya', 'salary': 540000, 'age': 25, 'dept': 'Sales'}

>>> Employee2

{'name': 'Diya', 'salary': 540000, 'dept': 'Sales'}

Making Shallow copy of a Dictionary: The copy() method of dictionaries creates a shallow
copy of dictionary.

(i) Shallow copy, where only the upper layer is copied and inner referenced object is not copied.

The dictionary method copy() is used as per the following syntax:

<dict>.copy()

Where, <dict> is the dictionary to be copied, -returns a shallow copy of the dictionary.

Example:

>>> Employee3=[Link]()

>>> Employee3

{'name': 'Diya', 'salary': 540000, 'dept': 'Sales'}

>>> Employee2

{'name': 'Diya', 'salary': 540000, 'dept': 'Sales'}

(ii) Deep copy, where all the layers are recursively copied and even inner referenced objects are
copied.
Example:
>>> Q= {'1': {'Name': 'Anusha'}, '2': ['Name', 'Harini']}
>>> import copy
>>> W = [Link](Q)
>>> W
{'1': {'Name': 'Anusha'}, '2': ['Name', 'Harini']}
>>> Q
{'1': {'Name': 'Anusha'}, '2': ['Name', 'Harini']}

Working of Copy:

Case-1: Creating copy using assignment operator: When we assign a dictionary name to
another name using assignment operator =, it does not create a copy internally. It will just make
two labels reference the same dictionary. Thus, any changes in either of the name will be reflected
in the other label.
>>> d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
>>> d1=d
>>> d1
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000}
>>> d
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000, 'Anil': 23000}
>>> d1['Anil']=23000
>>> d1
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000, 'Anil': 23000}
>>> d
{'Ramesh': 15000, 'Suresh': 20000, 'Akhilesh': 21000, 'Sameer': 22000, 'Anil': 23000}
Note: Making changes with any label will change the same dictionary and will be reflected
through both the labels.

Case-II: Creating copy using the copy() method: When we create a copy of a dictionary
using , copy() , a copy of keys is created with the new name and the values referenced are shared
by two copies.
→ If the VALUES referenced by the keys are immutable, then any changes made in the copy
created with copy() will not be reflected in the original dictionary.
Example:
>>> stu={1:'Sneha',2:'Neha',3:'Anusha'}
>>> Stu2=[Link]()
>>> stu
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> Stu2
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> Stu2[4]='Harini'
>>> stu
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> Stu2
{1: 'Sneha', 2: 'Neha', 3: 'Anusha', 4: 'Harini'}
→ If the values referenced by the keys are mutable (such as list), then the keys will be
referring to the same python list objects (i.e., the memory addresses of the values won’t change)
but lists being mutable can change.
Example:
>>> d1={1:[1,2,3],2:[3,4,5]}
>>> d2=[Link]()
>>> d1
{1: [1, 2, 3], 2: [3, 4, 5]}
>>> d2
{1: [1, 2, 3], 2: [3, 4, 5]}
>>> d2[1].append(4)
>>> d1
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
>>> d2
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
>>> d2[2].append(6)
>>> d1
{1: [1, 2, 3, 4], 2: [3, 4, 5, 6]}
>>> d2
{1: [1, 2, 3, 4], 2: [3, 4, 5, 6]}
>>> d1[1].append(5)
>>> d1
{1: [1, 2, 3, 4, 5], 2: [3, 4, 5, 6]}
>>> d2
{1: [1, 2, 3, 4, 5], 2: [3, 4, 5, 6]}

Deleting Elements from Dictionary:

1. pop(): This method removes and returns the dictionary element associated to passed key. The
pop() method will not only delete the key:value pair for mentioned key but also return the
corresponding value.
Syntax: <dict>.pop(key,<value>)
Example:
>>> Stu2
{1: 'Sneha', 2: 'Neha', 3: 'Anusha', 4: 'Harini'}
>>> [Link](2)
'Neha'
>>> Stu2
{1: 'Sneha', 3: 'Anusha', 4: 'Harini'}
>>> [Link](5)
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
[Link](5)
KeyError: 5
>>> [Link](5, 'No such key')
'No such key'
Note: with pop() we can specify your own return value in the form of a message or a value, in case
the given key is not found in the dictionary but with del statement, if the key is not in the dictionary,
it will raise the error.

2. popitem(): The popitem() removes and returns a (key,value) pair from the dictionary.
(i) It returns the last item entered in the dictionary.
(ii) The items will be removed from the dictionary in the LIFO (Last In First Out) order.
(iii) It returns the deleted key:value pair in the form of a tuple.
(iv) If the dictionary is empty, calling popitem() raises a KeyError.
Syntax: <dict>.popitem()
Where, <dict> is the name of the dictionary, and it returns the deleted key:value pair as tuple.
Example:
>>> stu
{1: 'Sneha', 2: 'Neha', 3: 'Anusha'}
>>> [Link]()
(3, 'Anusha')
>>> stu
{1: 'Sneha', 2: 'Neha'}

3. clear(): This method removes all items from the dictionary and the dictionary becomes empty.
Syntax: <dict>.clear()
Note: clear() method takes no arguments.
Example:
>>> [Link]()
>>> stu
{}

Get sorted list of keys: The sorted() function considers only the keys of the dictionary for
sorting and returns a sorted list of the dictionary keys.
Syntax: sorted(<dict>,[reverse=False])
Where,
<dict> name of the dictionary whose keys are to be sorted.
[reverse] argument is optional and when set to True, it will return the keys of the dictionary sorted
in descending order, default value of reverse is False.
Example:
>>> d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}
>>> f=sorted(d)
>>> f
['Akhilesh', 'Ramesh', 'Sameer', 'Suresh']
>>> e=sorted(d, reverse=True)
>>> e
['Suresh', 'Sameer', 'Ramesh', 'Akhilesh']
>>> g=sorted([Link]())
>>> g
['Akhilesh', 'Ramesh', 'Sameer', 'Suresh']
>>> g=sorted([Link]())
>>> g
[15000, 20000, 21000, 22000]
>>> h=sorted([Link]())
>>> h
[('Akhilesh', 21000), ('Ramesh', 15000), ('Sameer', 22000), ('Suresh', 20000)]
>>> d1={(1,2):'One',(3,4):'Two'}
>>> sorted(d1)
[(1, 2), (3, 4)]
Calculating Maximum, Minimum and Sum: Like lists and tuples, we can apply the max(), min(),
sum() functions on dictionaries too.
Syntax:
max(<dict>)
min(<dict>)
sum(<dict>)
Example:
>>> Stu2
{1: 'Sneha', 3: 'Anusha', 4: 'Harini'}
>>> min(Stu2)
1
>>> max(Stu2)
4
>>> sum(Stu2)
8
NOTE:
Difference between a Dictionary, Tuple and List
List Tuple Dictionary
A list is a sequence. A tuple is a sequence. A dictionary is a hash table of
key-value pair.
List is an ordered collection of Tuple is an ordered collection Dictionary is an unordered
items. of items collection.
List is mutable, i.e., it is Tuple is immutable. Addition Dictionary is mutable, i.e., it is
possible to add a new item or or deletion operations are not possible to add a new item or
delete an item from it. possible on tuple object delete an item from it.
List items are enclosed in Tuple items are enclosed in Dictionary items are enclosed
square brackets []. round brackets or parentheses in curly brackets {}.
().
List items are indexed. Tuple items are indexed. Items in dictionary are not
indexed.
Programs
1. Write a python program to arrange the values in a dictionary in ascending order.
Answer:
>>> d={1:21, 2:32, 3:25}
>>> print(sorted([Link]()))
[21, 25, 32]
>>> print(d)
{1: 21, 2: 32, 3: 25}
2. Write a python program to join/merge/concatenate the following two dictionaries
and create the new dictionary.
d1={1:'Amit',2:'Suman'} d2={4:'Ravi',5:'Kamal'}
Answer:
d1={1:'Amit',2:'Suman'} {1: 'Amit', 2: 'Suman', 4: 'Ravi', 5: 'Kamal'}
d2={4:'Ravi',5:'Kamal'}
d3={}
for i in (d1,d2):
[Link](i)
print(d3)
3. Write a function check(key) which takes a key as an argument and check whether
that key is present in dictionary or not.
Answer:
d1={1:'Amit',2:'Suman'} Key is present
def check(i):
for k in d1:
if k==i:
print("Key is present")
break
else:
print("Key is not present")
check(1)
4. Accept the number of terms say n from the user and display the dictionary in the
form of {n:n*5} for example:
If number of terms entered by user is 4 then the expected dictionary is
{1:5,2:10,3:15,4:20}
Answer:
d1={} Enter any number3
n=int(input("Enter any number")) {1: 5, 2: 10, 3: 15}
for i in range(n): Enter any number6
d1[i+1]=(i+1)*5 {1: 5, 2: 10, 3: 15, 4: 20, 5: 25, 6: 30}
print(d1)
5. Write a program to add the values of given dictionary.
d1={1:2, 2:90,3:50}
Answer:
>>> d1={1:2, 2:90,3:50}
>>> print(sum([Link]()))
142
6. Write a program to add keys of given dictionary.
d1={1:2, 2:90,3:50}
Answer:
>>> d1={1:2, 2:90,3:50}
>>> print(sum([Link]()))
6
7. Write a program to multiply all the values of given dictionary. d1={1:2, 2:90,3:50}
Answer:
d1={1:2, 2:90,3:50} 6
s=1
for i in d1:
s=s*i
print(s)
8. Write a program to accept a key from the user and remove that key from the
dictionary if present.
d1={1:2,2:90,3:50} Enter any key5
k=int(input("Enter any key")) Key not found
if k in d1: Enter any key3
[Link](k) {1: 2, 2: 90}
print(d1)
else:
print("Key not found")
9. Write a program in python to display the maximum and minimum value in
dictionary.
Answer:
d1={1:21,2:90,3:50} Maximum Value is 90
mx=max([Link]()) Minimum Value is 21
mn=min([Link]())
print("Maximum Value is", mx)
print("Minimum Value is", mn)
10. Write a program in python to remove the duplicate values from the dictionary as
per the following example.
Original Dictionary= d1={1:"Aman", 2:"Suman", 3:"Aman"}
New Dictionary={1: 'Aman', 2: 'Suman'}
Answer:
d1={1:"Aman", 2:"Suman", 3:"Aman"} {1: 'Aman', 2: 'Suman'}
nd1={}
for k,v in [Link]():
if v not in [Link]():
nd1[k]=v
print(nd1)
11. Write a program to count the number of elements in a dictionary.
Answer:
d1={1:"Aman", 5
2:"Suman",3:"Aman",4:"Amit",5:"Sumit"}
print(len(d1))
12. Accept a key from the user to modify its value.
Answer:
d1={1:"Aman",2:"Suman",3:"Aman",4:"Amit",5:"Sumit"} Enter the key1
k=int(input("Enter the key")) Enter the Modified ValueRiyaz
v=input("Enter the Modified Value") {1: 'Riyaz', 2: 'Suman', 3: 'Aman', 4:
d1[k]=v 'Amit', 5: 'Sumit'}
print(d1) Enter the key5
Enter the Modified ValueHarini
{1: 'Aman', 2: 'Suman', 3: 'Aman', 4:
'Amit', 5: 'Harini'}
13. Write a program to store information of products like product id, product name and
product price in a dictionary by taking product id as a key.
Answer:
t=int(input("Enter Number of terms")) Enter Number of terms2
prod={} Enter Product id1
for i in range(t): Enter Product NameNutella
pid=int(input("Enter Product id")) Enter Product Price200
pn=input("Enter Product Name") Enter Product id2
pp=int(input("Enter Product Price")) Enter Product NamePeanut Butter
temp=(pn,pp) Enter Product Price150
prod[pid]=temp {1: ('Nutella', 200), 2: ('Peanut Butter', 150)}
print(prod)
14. Write a program to accept the employee id from the user and display its details
from the dictionary. Data is stored in the dictionary in the following format.
{Empid:(Empname, EmpSalary)}
Answer:
emp={1:("Amit",25000),2:("Suman",30000),3:("Ravi",36000)} Enter the product id1
pid=int(input("Enter the product id")) Employee id, Employee Name
i=[] Salary
if pid in emp: 1 Amit
i=emp[pid] 25000
print("Employee id, Employee Name","\t""Salary")
print(pid,"\t\t",i[0],'\t\t',i[1])
else:
print("Record not found")
15. Write a program to display the name of all the employees whose salary is more than
25000 from the following dictionary.
emp={1:("Amit",25000),2:("Suman",30000),3:("Ravi",36000)}
Format of data is given below:
Answer:
emp={1:("Amit",25000),2:("Suman",30000),3:("Ravi",36000)} Employees whose salary is more
d=list([Link]()) than 25000 is/are
print("Employees whose salary is more than 25000 is/are") Suman
for i in d: Ravi
if i[1]>25000:
print(i[0])
16. Write a program to count the frequency of each word in a given string accepted
from the user using dictionary.
Answer:
str1=input("Enter any String") Enter any StringIndia is my country i love my
w=[Link]() country India
d={} Frequency of India is 2
for i in w: Frequency of is is 1
if i not in d: Frequency of my is 2
d[i]=[Link](i) Frequency of country is 2
for i in d: Frequency of i is 1
print("Frequency of",i,"is",d[i]) Frequency of love is 1
17. Write a program to accept roll number, names and marks of five students and store
the details in dictionary using roll number as key. Also display the sum of marks of all
the five students.
Answer:
d={} Enter roll number1
s=0 Enter NameAmit
for i in range(5): Enter marks25
rn=int(input("Enter roll number")) Enter roll number2
nm=input("Enter Name") Enter NameSumit
mrk=input("Enter marks") Enter marks25
temp=(nm,mrk) Enter roll number3
d[rn]=temp Enter NameHarini
for i in d: Enter marks30
L=d[i] Enter roll number4
s=s+int(L[1]) Enter NameAnusha
print("Sum of Marks ",s) Enter marks27
Enter roll number5
Enter NameTeja
Enter marks20
Sum of Marks 25
Sum of Marks 50
Sum of Marks 80
Sum of Marks 107
Sum of Marks 127
18. Write a program to count the frequency of each character in a given string accepted
form the user using dictionary. (Store the character as key and its frequency as value)
Answer:
str1=input("Enter any string") Enter any stringEngineering
d={} Frequency of E is/are 1
for i in str1: Frequency of n is/are 3
if i not in d: Frequency of g is/are 2
d[i]=[Link](i) Frequency of i is/are 2
for i in d: Frequency of e is/are 2
print("Frequency of",i, "is/are",d[i]) Frequency of r is/are 1

You might also like