Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Revision Tour of Python Class XII

Uploaded by

hasanfazil953
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Revision Tour of Python Class XII

Uploaded by

hasanfazil953
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Revision Tour of python class XI

Basics of Python
Observe the program first then memorize the definitions:

Python keyword/ reserve words


Keywords are reserve 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. As Python is case sensitive, keywords
must be written exactly.
Identifiers
In programming languages, identifiers are names used to identify (Name) a variable, function, or other entities in a
program. The rules for naming an identifier in Python are as follows:

➔ The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).

➔ This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_) Thus, an identifier
cannot start with a digit.

➔ It can be of any length. (However, it is preferred to keep it short and meaningful).

➔ It should not be a keyword or reserve word.

➔ We cannot use special symbols like !, @, #, $, %, etc., in identifiers.


Variables
A variable in a program is uniquely identified by a name (identifier). 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 (e.g., ‘b’, ‘Global Citizen’),
numeric (e.g., 345) or any combination of alphanumeric characters (CD67). In Python we can use an assignment
statement to create new variables and assign specific values to them.
Comments
Comments are used to add a remark or a note in the source code. Comments are not executed by interpreter.
Comments in python can be created as:

➔ for single line comment use # (hash symbol)

➔ for multi line comment use ‘‘‘ text ’’’ (in triple quotes)
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data values a variable can
hold and the operations that can be performed on that data.
Number
Number data type stores numerical values only. It is further classified into three different types: int, float and
complex.
Try the following statements on system in shell mode and observe the output:
num1 = 10 #(integer positive value )
type(num1)
num2 = -1210 #(integer negative value)
type(num2)
float1 = -1921.9 #(float1 variable contain decimal value so it contains float value)
type(float1)
float2 = -9.8*10**2 #(float2 variable contain decimal value so it contains float value)
print(float2, type(float2))
var2 = -3+7.2j #(var2 variable contain complex value)
print(var2, type(var2))
Boolean
var3= True # (var3 variable contain Boolean Value)
print(type(var3)) # print type Bool
Variables of simple data types like int, float, boolean, etc. hold single values. But such variables are not useful to
hold a long list of information, for example, names of the months in a year, names of students in a class, names and
numbers in a phone book or the list of artefacts in a museum. For this, Python provides data types like tuples, lists,
dictionaries and sets.
Sequences can used as datatype in python
A Python sequence is an ordered collection of items, where each item is indexed by an integer. The three types of
sequence data types available in Python are Strings, Lists and Tuples. A brief introduction to these data types is as
follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special characters including spaces.
String values are enclosed either in single quotation marks (e.g., ‘KV’) or in double quotation marks (e.g.,
“Vidyalaya”). The quotes are not a part of the string, they are used to mark the beginning and end of the string for
the interpreter. For example:
Write your examples here:
Prove this statement using proper example: We cannot perform numerical operations on strings, even when the
string contains a numeric value.
(B) List
List is a sequence of items separated by commas and the items are enclosed in square brackets [ ]. In list we can
change the items so we can say it’s a mutable datatype
#To create a list
list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1) # printing the elements of list1
Output: [5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).Once created, we
cannot change the tuple (Records cannot be changed) – i.e. we can say immutable datatype.
Tuple can be defined as
T=5,
T=(5,)
T=5,6,7,8
T= ‘a’,’b’,’c’,5,6,7
T=(5,6,’r’,’s’,’wel’)
#create a tuple tuple1
tuple1 = (10, 20, "KV", 5.5, 'a')
print(tuple1) #printing the elements of the tuple tuple1
Output: (10, 20, "KV", 5.5, 'a')
(D) Dictionary
Dictionary in Python holds data items in key : value pairs. Items in a dictionary are enclosed in curly braces { }.
Every key is separated from its value using a colon (:) sign. The key : value pairs of a dictionary can be accessed
using the key. The keys are usually strings and their values can be any data type. In order to access any value in the
dictionary, we have to specify its key in square brackets [ ].
#create a dictionary
dict1 = {'Fruit':'Apple', 1:'Monday', 'Price Rs':120}
print(dict1)
output: {'Fruit': 'Apple', 1: ‘Monday’,'Price Rs': 120}
print(dict1['Price Rs'])
output: 120
print(dict1[1])
output:’Monday’
(E) None
None is a special data type with a single value. It is used to signify the absence of value in a situation. None
supports no special operations, and it is neither False nor 0 (zero).
myVar = None
print(type(myVar))
<class 'NoneType'>
print(myVar)
Mutable and Immutable Data Types
Variables whose values can be changed after they are created and assigned without changing their memory location
are called mutable. Variables whose values cannot be changed after they are created and assigned or upon changing
values their memory location is changed, are called immutable. When an attempt is made to update the value of an
immutable variable, the old variable is destroyed and a new variable is created by the same name in new memory
location.
Exercise: Define a variable by assigning a value, find and note its ID, change the value and again find its ID, now
observe the difference and do it for different data types.
Precedence of Operators
Evaluation of the expression is based on precedence of operators. When an expression contains different kinds of
operators, precedence determines which operator should be applied first. Higher precedence operator is evaluated
before the lower precedence operator. (Simply apply BODMAS rules)
Order of Precedence (higher to lower)

Flow of Control
Selection
The if statement has following syntaxes:
1)
if condition:
statement(s)
2) else:
if condition: statement(s)
statement(s)
3) if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
NOTE
Indentation
Python uses indentation for block as well as for nested block structures. Leading whitespace
(spaces and tabs) at the beginning of a statement is called indentation. In Python, the same level of
indentation associates statements into a single block of code. The interpreter checks indentation
levels very strictly and throws up syntax errors if indentation is not correct. It is a common
practice to use a single tab for each level of indentation.
Repetition
Repetition of a set of statements in a program is made possible using looping constructs.
The ‘for’ Loop
The for statement is used to iterate over a range of values or a sequence. The for loop is executed
for each of the items in the range. These values can be either numeric, or they can be elements of
a data type like a string, list, tuple or even dictionary.
Syntax of the for Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
The ‘while’ Loop
The while statement executes a block of code repeatedly as long as the control condition of the
loop is true. The control condition of the while loop is executed before any statement inside the
loop is executed. After each iteration, the control condition is tested again and the loop continues
as long as the condition remains true. When this condition becomes false, the statements in the
body of loop are not executed and the control
is transferred to the statement immediately following the body of while loop. If the condition of
the while loop is initially false, the body is not executed even once.
Syntax of while Loop
while test_condition:
body of while
Break and Continue Statement
In certain situations, when some particular condition occurs, we may want to exit from a loop
(come out of the loop forever) or skip some statements of the loop before continuing further in the
loop. These requirements can be achieved by using break and continue statements, respectively.

STRINGS IN PYTHON
Python strings are characters enclosed in quotes of any type – single quotation marks, double
quotation marks and triple quotation marks. An empty string is a string that has 0 characters.
Python strings are immutable.
Strings are sequence of characters, where each character has a unique position-id/index. The
indexes of a string begin from 0 to (length -1) in forward direction and -1,-2,-3,….,-length in
backward direction.
STRING SLICES
In Python, the term ‘string slice’ refers to a part of the string, where strings are sliced using a
range of indices. That is, for a string say name, if we give name[n:m] where n and m are integers
and legal indices, Python will return a slice of the string by returning the characters falling
between indices n and m starting at n, n+1, n+2, … till m-1.

Then,
word[0:7] will give ‘amazing’
word[0:3] will give ‘ama’
word[2:5] will give ‘azi’
word[-7:-3] will give ‘amaz’
word[-5:-1] will give ‘azin’
In a string slice, you give the slicing range in the form [<begin-index>:<last>]. If, however, you
skip of the begin-index or last, Python will consider the limits of the string, i.e., for missing begin
index, it will consider 0 (the first index) and for mission last value, it will consider length of the
string. Consider the following examples to understand this:
word[:7] will give ‘amazing’
word[:5] will give ‘amazi’
word[3:] will give ‘zing’
word[5:] will give ‘ng’
Note: Using the same string slicing technique, you will find that for any index n, s[:n]+s[n:] will
give you original string s.
STRING FUNCTIONS AND METHODS

Every string object that you create in Python is actually an instance of String class. The string
manipulation methods that are being discussed below can be applied to string as per following
syntax:
<stringObject>.<methodname>()
1. string.capitalize(): Returns a copy of the string with its first character capitalized
Exmple: ‘true’.capitalize() will return ‘True’
‘i love my India’.capitalize() will return ‘I love my India’
2. string.title(): Returns a copy of the string with first character of each work capitalized.
Example: ‘true’.title() will return ‘True’
‘i love my india’.capitalize() will return ‘I Love My India’
3. string.upper(): Returns a copy of the string converted to uppercase. Examples:
string.upper() will return ‘HELLO’
string2.upper() will return ‘THERE’
string3.upper() will return ‘GOLDY’
4. string.lower(): Returns a copy of the string converted to lowercase. Examples:
string.lower() will return ‘hello’
string2.lower() will return ‘there’
string3.lower() will return ‘goldy’
5. string.count(str): Returns the count of an string in the given string. Examples:
‘I love my india’.count(‘i’) will return 2
‘it goes as – ringa ringa roses’.count(‘ringa’) will return 2
6. string.find(sub[,start,end]): Returns the lowest index in the string where the substring sub is
found within the slice range of start and end. Returns -1 if sub is not found. Example:
string = ‘it goes as – ringa ringa roses’
sub = ‘ringa’
string.find(sub) will return 13
string.find(sub,15,22) will return -1
string.find(sub,15,25) will return 19
7. string.index(str): Returns the lowest index in the sting where the substring is found. Example:
‘I love my India’.index(‘o) will return 3
‘I love my India’.index(‘my’) will return 7
8. string.isalnum(): Returns True if the characters in the string are alphanumeric (alphabets or
numbers) and there is at least one character, False otherwise. Example:
string =”abc123”
string2 = ‘hello’
string3 = ‘12345’
string4 = ‘ ’
string.isalnum() will return True
string2.isalnum() will return True
string3.isalnum() will return True
string4.isalnum() will return False
9. string.islower(): Returns True if all cased characters in the string are lowercase. Examples:
string = ‘hello’
string2 = ‘THERE’
string3 = ‘Goldy’
string.islower() will return True
string2.islower() will return False
string3.islower() will return False
10. string.isupper(): Returns True if all cased characters in the string are uppercase. Examples:
string.isupper() will return False
string2.isupper() will return True
string3.isupper() will return False
11. string.isspace(): Returns True if there are only whitespace characters in the string. Examples:
string = “ “
string2 = “”
string.isspace() will return True
string2.isspace() will return False
12. string.isalpha(): Returns True if all characters in the string are alphabetic and there is at least
one character, False otherwise. Example:
string.isalpha() will return False
string2.isalpha() will return True
string3.isalpha() will return False
13. string.isdigit(): Returns True if all the characters in the string are digits. There must be at least
one character, otherwise it returns False. Example:
string.isdigit() will return False
string2.isdigit() will return False
string3.isdigit() will return True
14. string.split([<sep>]): This function splits the string to form a list of strings.
If we do not provide any argument to split then by default it will split the given string considering
whitespace as a separator, e.g.,
“I Love Python”.split() will give [‘I’, ‘Love’, ‘Python’]
If we provide a string or a character as an argument to split(), then the given string is divided into
parts considering the given string/character as separator and separator character is not included in
the split strings, e.g.,
“I Love Python”.split(‘o’) will give [‘I L’, ’ve Pyth’, ’n’]
15. string.partition(<sep>): The partition() method searches for a specified string, and splits the
string into a tuple containing three elements. The first element contains the part before the
specified string. The second element contains the specified string. The third element contains the
part after the string.
Example: ‘I Love my India’.partition(‘my’) will give (‘I Love ’, ‘my’, ‘ India’)
16. string.lstrip([chars]): Returns a copy of the string with leading characters removed.
If used without any argument, it removes the leading whitespaces.
One can use optional chars argument to specify a set of characters to be removed.
The chars argument is not a prefix; rather, all combinations of its values (all possible substrings
from the given string argument chars) are stripped when they lead the string.
Examples:
string = “hello”
string.lstrip() will return ‘hello’
string2 = ‘There’
string2.lstrip(‘the’) will return ‘There’
string2.lstrip(‘The’) will return ‘re’
string2.lstrip(‘he’) will return ‘There’
string2.lstirp(‘Te’) will return ‘here’
string2.lstrip(‘Teh’) will return ‘re’
string2.lstrip(‘heT’) will return ‘re’
“saregamapadhanisa”.lstrip(“tears”) will return ‘gamapadhanisa’
“saregamapadhanisa”.lstrip(“races”) will return ‘gamapadhanisa’
17. string.rstrip([chars]): Returns a copy of the string with trailing characters removed.
If used without any argument, it removes the trailing whitespaces.
The chars argument is a string specifying the set of characters to be removed.
The chars argument is not a suffix; rather, all combinations of its values are stripped.
Examples:
string = ‘hello’
string.rstrip() will return ‘hello’
string2 = ‘There’
string2.rstripe(‘ere’) will return ‘Th’
string2.rstrip(‘care’) will return ‘Th’
string2.rstrip(‘car’) will return ‘there’
“saregamapadhanisa”.rstrip(“tears”) will return “saregamapadhani”
“saregamapadhanisa”.rstrip(“races”) will return “saregamapadhani”
18. string.strip([chars]): Returns a copy of the string with both leading and trailing characters
removed.

If used without any argument, it removes leading and trailing whitespaces.


The chars argument is a string specifying the set of characters to be removed.
The chars argument is not a suffix; rather, all combinations of its values are stripped.
Examples:
string = ‘ hello ‘
string.strip() will return ‘hello’
string2=’xxThis is a stringxx’
string2.strip(‘x’) will return ‘This is a string’
19. <str>.replace(<old string>,<new string>): This functions replaces all occurrences of <old
string> with <new string> in the given string, e.g.,

“I Love Python”.replace(“Python”,”Programming”) will give ‘I Love Programming’


20. len(string): One more function that you have used with string is len() function which gives
you the length of the string as the count of characters contained in it. Recall that you use it as:
len(<string>)

For example,
string=’hello’
len(string) will return 5

LISTS IN PYTHON
The Python lists are containers that are used to store a list of values of any type. Python lists are
mutable i.e., you can change the elements of a list in place. Which means Python will not create a
fresh list when you make changes to an element of a list. List is a type of sequence like strings and
tuples.
Difference from Strings
You cannot change individual elements of a string in place, but Lists allow you to do so. That is,
following statement is fully valid for Lists:
L[i] = <element>
For example, consider the same vowels list crated above. Now if you want to change some of
these vowels, you may write something as show below:
vowels[0] = ‘A’
print(vowels)
[‘A’,’e’,’i',’o’,’u’]
List Functions
1. len() function
This function returns the length of a list i.e. this function returns number of elements present in the
list. It is used as per following format:
len(<list>)
For example for a list L1 = [13,18,11,16,18,14]
len(L1) will return 6
2. list() function

This function converts the passed argument to a list. The passed argument could be a string, a list
or even a tuple. It is used as per following format:
list(<argument>)
For example for a string s = “Computer”
list(s) will return [‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
3. The append() function

The append() function adds an item to the end of the list. It works as per following syntax:
List.append(<item>)
For example, to add a new item “yellow” to a list containing colours, you may write:
colours =[“red”,”green”,”blue”]
colours.append(“yellow”)
print(colours)
[“red”,”green”,”blue”,”yellow”]
4. The extend() function

The extend() method is also used for adding multiple elements (given in the form of a list) to a
list. The extend() function works as per following format:
List.extend(<list>)
That is extend() takes a list as an argument and appends all of the elements of the argument list to
the list object on which extend() is applied. Consider following example:
t1=[‘a’,’b’,’c’]
t2=[‘d’,’e’]
t1.extend(t2)
print(t1)
[‘a’,’b’,’c’,’d’,’e’]
print(t2)
[‘d’,’e’]
5. The insert() function

If you want to insert an element somewhere in between or any position of your choice, both
append() and extend()are of no use. For such a requirement insert() is used.

The insert() function inserts an item at a given position. It is used as per following syntax:
List.insert(<pos>,<item>)
The first argument <pos> is the index of the element before which the second argument <item> to
be added. Consider the following example:
t1=[‘a’,’e’,’u’]
t1.insert(2,’i')
print(t1)
[‘a,’e’,’i',’u’]
For function insert(), we can say that:
list.insert(0,x) will insert element x at the front of the list i.e. at index 0.
list.insert(len(list),x) will insert element x at the end of the list i.e. index equal to length of the list
6. The count() function
This function returns the count of the item that you passed as argument. If the given item is not in
the list, it returns zero. It is used as per following format:
List.count(<item>)
For instance:
L1 = [13,18,20,10,18,23]
print(L1.count(18))
2
print(L1.count(28))
0
7. The Index() function
This function returns the index of first matched item from the list. It is used as per following
format:
List.index(<item>)
For example, for a list L1 = [13,18,11,16,18,14]
print(L1.index(18))
1
However, if the given item is not in the list, it raises exception ValueError.
8. The remove() function
The remove() method removes the first occurrence of given item from the list. It is used as per
following format:
List.remove(<value>)
The remove() will report an error if there is no such item in the list. Consider the example:
t1=[‘a’,’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘a’)
print(t1)
[’e’,’i',’p’,’q’,’a’,’q’,’p’]
t1.remove(‘p’)
print(t1)
[’e’,’i',’q’,’a’,’q’,’p’]
print(t1.remove(‘k’))
ValueError
9. The pop() method
The pop() is used to remove the item from the list. It is used as per the following syntax:
List.pop(<index>)
Thus, pop() removes an element from the given position in the list, and return it. If no index is
specified, pop() removes and returns the last item in the list.
t1 = [‘k’,’a’,’i',’p’,’q’,’u’]
ele = t1.pop(0)
print(ele)
‘k’
10. The reverse() function
The reverse() reverses the item of the list. This is done “in place” i.e. id does not create a new list.
The syntax to use reverse method is:
List.reverse()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.reverse()
print(t1)
[‘p’,’q’,’a’,’q’,’i',’e’]
11. The sort() function
The sort() function sorts the items of the list, by default in increasing order. This is done “in
place” i.e. it does not create a new list. It is used as per following syntax:
List.sort()
For example:
t1 = [‘e’,’i',’q’,’a’,’q’,’p’]
t1.sort()
print(t1)
[‘a’,’e’,’i',’p’,’q’,’q’]
To sort a lit in decreasing order using sort(), you can write:
List.sort(reverse=True)
12. min() function

This function returns the minimum value present in the list. This function will work only if all
elements of the list are numbers or strings. This function gives the minimum value from a given
list. Strings are compared using its ordinal values/Unicode values. This function is used as per
following format:
min(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
min(L1) will return 11 and min(L2) will return ‘U’
13. max() function

This function returns the maximum value present in the list. This function will work only if all
elements of the list are numbers or strings. This function gives the maximum value from a given
list. Strings are compared using its ordinal values/Unicode values. This function is used as per
following format:
max(<list>)
For example L1 = [13,18,11,16,18,14] and L2 = [‘a’, ‘e’ ‘i', ‘o’ ,’U’] then
max(L1) will return 18 and max(L2) will return ‘o’
14. sum() function

This function returns the total of values present in the list. This function will work only if all
elements of the list are numbers. This function gives the total of all values from a given list. This
function is used as per following format:
sum(<list>)
For example L1=[13,18,11,16,18,14] then sum(L1) will return 90
15. The clear() function

This method removes all the items from the list and the list becomes empty list after this function.
This function returns nothing. It is used as per following format:
List.clear()
For instance:
L1=[2,3,4,5]
L1.clear()
print(L1)
[]

Introduction to Python Tuples


Python tuples are immutable i.e. you cannot change the elements of a tuple in place; Python will
create a fresh tuple when you make changes to an element of a tuple.
Unpacking Tuples
Creating a tuple from a set of values is called packing and its reverse i.e., creating individual
values from a tuple’s element is called unpacking.
Unpacking is done as per syntax:
<variable1>,<variable2>,<variable3>,…. = t
where the number of variables in the left side of assignment must match the number of elements
in the tuple. For example, if we have a tuple as:
t = (1, 2, ‘A’, ‘B’)
The length of above tuple t is 4 as there are four elements in it. Now to unpack it, we can write
w,x,y,z = t
Python will now assign each of the elements of tuple t to the variables on the left side of
assignment operator. That is, you can now individually print the values of these variables
somewhat like:
print(w)
print(x)
print(y)
print(z)
The above code will yield the result as
1
2
‘A’
‘B’
Tuple functions
1. The len() funtion
This method returns length of tuple i.e. the count of elements in the tuple. Its syntax is:
len(<tuple>)
For example:
emp = (‘John’, 10000, 24, ‘Sales’)
print(len(emp))
4
2. The max() function
This method returns the element from the tuple having maximum value. Its syntax is:
max(<tuple>)
Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(max(tp1))
34
tp2 = (“Karan”, “Zubin”, “Zara”, “Ana”)
print(max(tp2))
Zubin
Please note that max() applied on sequences like tuples/lists etc. will return a maximum value
ONLY IF the sequence contains values of same type.
3. The min() function
This method returns the element from the tuple having minimum value. Its syntax is:
min(<tuple>)
Example:
tp1 = (10,12,14,20,22,24,30,32,34,-2)
print(min(tp1))
-2
tp2 =(“Karan”, “Zubin”, “Zara”, “Ana”)
print(min(tp2))
Ana
Like max(), for min() to work, the element of tuple should be of same type.
4. The index() function
The index() works with tuples in the same way it works with lists. That is, it returns the index of
an existing element of a tuple. It is used as:
<tuplename>.index(<item>)
Example:
t1 =(3,4,5,6.0)
print(t1.index(5))
2
5. The count() function
The count() method returns the count of a member element/object in a given sequence (list/tuple).
You can use the count() function as per following syntax:
<sequence name>.count(<object>).
Example:
t1=(2,4,2,5,7,4,8,9,9,11,7,2)
print(t1.count(2))
3
t1.count(7)
2
For an element not in tuple, it returns 0.
6. The tuple() function
This method is actually constructor method that can be used to crate tuples from different types of
values. Syntax:
tuple(<sequence>)
Example:
a. Creating empty tuple
>>>tuple()
()
b. Creating a tuple from a string
t = tuple(“abc”)
print(t)
(‘a’,’b’,’c’)
c. Creating a tuple from a list
t = tuple([1,2,3])
print(t)
(1,2,3)
d. Creating a tuple from keys of a dictionary
t1 = tuple({1:”1”, 2:”2”})
print(t1)
(1,2)
7. The sorted() function
This function is used to take a tuple as argument and converts this tuple to a sorted list. It has
another argument called reverse. If reverse is set to True then tuple is sorted in descending order
otherwise tuple will be sorted in ascending order. Syntax:
sorted(<tuple>[,reverse = True])
t1 =(3,4,5,6,0)
print(sorted(t1))
[0, 3, 4, 5, 6]
print(sorted(t1, reverse = True))
[6, 5, 4, 3, 0]
Indirectly Modifying Tuples
(a) Using Tuple Unpacking
Tuples are immutable. To change a tuple, we would need to first unpack it, change the values, and
then again repack it:
tp1 = (11,33,66,99)
1. First unpack the tuple
a,b,c,d = tp1
2. Redefine or change desired variable say, c
c=77
3. Now repack the tuple with changed value
tp1 = (a,b,c,d)
(b) Using the constructor functions of lists and tuples i.e., list() and tuple()
There is another way of doing the same as explained below:
tp1 = (“Anand”,35000,35,”Admin”)
1. Convert the tuple to list using list():
lst = list(tp1)
2. Make changes in the desired element in the list
lst[1] = 45000
3. Create a tuple from the modified list with tuple()
tp1 = tuple(lst)
Dictionary
Dictionaries are mutable unordered collections with elements in the form of a {key:value pairs
that associate keys to values.
Characteristics of a Dictionary
1. Unordered Set: A dictionary is a unordered set of key:value pairs. Its values can contain
references to any type of object.
2. Not a sequence: Unlike a string, list and tuple, a dictionary is not a sequence because it is
unordered set of elements.
3. Indexed by Keys, Not Numbers: Dictionaries are indexed by keys and not by any index like in
sequences.
4. Keys must be unique: Each of the keys within a dictionary must be unique. Since keys are used
to identify values in a dictionary, there cannot be duplicate keys in a dictionary. However, two
unique keys can have same values, e.g. consider the BirdCount dictionary here:
BirdCount = {“Finch”:10, “Myna”:13, “Parakeet”:16, “Hornbill”:15, “Peacock”:15}
5. Mutuable: Like lists, dictionaries are also mutable. We can change the value of a certain key “in
place” using the assignment as per syntax:
<dictionary>[<key>] = <value>
For example,
>>>dict1[“3”]
“Yamuna”
>>>dict1[“3”] = “Ganga”
>>>dict1[“3”]
‘Ganga’
6. Internally stored as Mappings: Internally, the key:value pairs of a dictionary are associated with
one another with some internal function (called hash function).this way of linking is called
mapping.
Dictionary functions
1. The len() function
This method returns length of the dictionary, i.e., the count of elements (key:value pairs) in the
dictionary. The syntax to use this method is given below:
len(<dictionary>)
For example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(len(Employee))
3
2. The clear() function
This method removes all items from the dictionary and the dictionary becomes empty dictionary.
The syntax to use this method is given below:
<dictionary>.clear()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
Employee.clear()
print(Employee)
{}
3. The get() function
With this method, you can get the item with the given key, similar to dictionary[key], If the key is
not present Python by default gives error, but you can specify your own message through default
argument as per following syntax:
<dictionary>.get(<key>,[default])
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24, ‘dept’:’Sales’}
print(Employee.get(‘dept’))
Sales
print(Employee.get(‘designation’))
NameError:name ‘designation’ is not defined
>>>Employee.get(‘designation’, “Error! Key not found”)
Error! Key not found
4. The items() function
This function returns all of the items in the dictionary as a sequence of (key, value) tuples. Note
that these are returned in no particular order
<dictionary>.items()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
myList = employee.items()
for x in myList:
print(x)
The output of the above code will be like:
(‘salary’, 10000)
(‘age’, 24)
(‘name’, ‘John’)
5. The keys() method
This method returns all of the keys in the dictionary as a sequence of keys in form of a list. Syntax
to use this method is:
<dictionary>.keys()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(Employee.keys())
[‘salary’,’age’,’name’]
6. The values() function
This method returns all the values from the dictionary as a list. The syntax to use this method is
given below:
<dictionary>.values()
Example
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(Employee.values())
[‘Jhon’,10000,24,]
7. The update() function
This function 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(overwrite) any item already there with the same keys. The syntax to use this method is
given below:
<dictionary>.update(<other-dictionary>)
Example:
Employee1 = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
Employee2 = {‘name’:’Diya’, ‘salary’:54000, ‘dept’:’Sales’}
Employee1.update(Employee2)
print(Employee1)
{‘salary’:54000, ‘dept’:’Sales’, ‘name’:’Diya’, ‘age’:24}
8. The fromkeys() function
This method creates a dictionary from the given sequence of keys and a value. It assigns same
value for all keys. If value is not given then it assigns None as the value of all keys. Its syntax is:
<dict-var> = dict.fromkeys(<key-sequence> [,<value>])
For example:
month = [‘Jan’, ‘Mar’, ‘May’]
d1 = dict.fromkeys(month, 31)
print(d1)
will give us:
{'Jan': 31, 'Mar': 31, 'May': 31}
and
d2 = dict.fromkeys(month)
print(d2)
will give us:
{'Jan': None, 'Mar': None, 'May': None}
9. The copy() function
This method creates a copy of the dictionary. This method does not make any change in the
original dictionary. It only makes a copy of this dictionary. Its syntax is:
<dict-var> = <original-dict>.copy()
For example:
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
d2 = d1.copy()
print(d2)
will give us:
{‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
10. The pop() function
Like lists pop() method removes an element from a dictionary. This method removes a key:value
pair from the dictionary and returns the value removed. For this a key need to be specified. This
method also has an optional argument for default value if the key is not present in the dictionary.
Its syntax is:
<dict>.pop(<key>[,<default-value>])
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
print(d1.pop(‘Jan’))
31
d1.pop(‘Jul’,”Element not present”)
Element not present
11. The popitem() function
In Python 3.7 and higher version this method of dictionary removes the last inserted key:value
pair from the dictionary and return it as a tuple. Its syntax is:
<dict>.popitem()
For example:
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
print(d1.popitem())
(‘Mar’, 31)
12. The setdefault() method
This method of dictionary takes two arguments key and default-value. If key is found in the
dictionary then it returns its corresponding value. If key is not found in the dictionary then it
inserts the default-value with key in the dictionary and returns default-value. If default-value is
not given then None is inserted as default-value of the key and returns nothing. Its syntax is:
<dict>.setdefault(<key>[,<default-value>])
For example:
>>>d1={'Jan':31, 'Feb':28, 'Mar':31}
>>>d1.setdefault('Jan')
31
>>>d1.setdefault('Apr',30)
30
>>>d1.setdefault('May')
>>>d1
{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': None}
13. The max() function
This function when applied with dictionary returns the maximum key value of all keys of
dictionary.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
print(max(d1))
‘Mar’
14. The min() function
This function when applied with dictionary returns the smallest key value of all keys of
dictionary.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
print(min(d1))
‘Feb’
15. The sorted() function
This function returns the keys of the dictionary in ascending order in the form of a list.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
sorted(d1)
['Feb', 'Jan', 'Mar']
For getting result in descending order use reverse=True with sorted() function.
sorted(d1,reverse=True)
['Mar', 'Jan', 'Feb']

You might also like