Python Revision Tour Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Python Revision Tour Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Contents show

Python Revision Tour Class 12 Notes

Token in Python

The smallest unit in a Python programme is called a token. In python all the instructions and statements in a program are built with tokens. Different type of tokens in python are keywords, identifier, Literals/values, operators and punctuators –

Keywords

Words with a particular importance or meaning in a programming language are known as keywords. They are utilised for their unique qualities. There are 33 keywords in Python True, False, class, break, continue, and, as, try, while, for, or, not, if, elif, print, etc.

Identifiers

The names assigned to any variable, function, class, list, method, etc. for their identification are known as identifiers. Python has certain guidelines for naming identifiers and is a case-sensitive language. To name an identifier, follow these guidelines: –

  1. Code in python is case – sensitive
  2. Always identifier starts with capital letter(A – Z), small letter (a – z) or an underscore( _ ).
  3. Digits are not allowed to define in first character but you can use between.
  4. No whitespace or special characters are allowed.
  5. No keyword is allowed to define identifier.

Literals or Values

In Python, literals are the raw data that is assigned to variables or constants during programming. There are five different types of literals string literals, numeric literals, Boolean literals and special literals none.

a) String literals

The string literals in Python are represented by text enclosed in single, double, or triple quotations. Examples include “Computer Science,” ‘Computer Science’, ”’Computer Science”’ etc.
Note – Triple quotes string is used to write multiple line.
Example –
n1 = ‘Computer Science’
n2 = “Computer Science”
n3 = ”’Computer Science”’
print(n1)
print(n2)
print(n3)

b) Numeric Literals

Literals that have been use to storing numbers is known is Numeric Literals. There are basicaly three numerical literals –

  1. Integer Literal
  2. Float Literal
  3. Complex Literal

Example
num1 = 10
num2 = 15.5
num3 = -20
print(num1)
print(num2)
print(num3)

c) Boolean Literal

Boolean literals have only two values True of False.
Example
num = (4 == 4)
print(num)

d) Special literals none

The special literal “None” in Python used to signify no values, the absence of values, or nothingness.
Example
str = None
print(str)

Operators

In Python, operators are specialized symbols that perform arithmetic or logical operations. The operation in the variable are applied using operands.

The operators can be arithmetic operators(+, -, * /, %, **, //), bitwise operators (&, ^, |), shift operators (<<, >>), identity operators(is, is not), relational operators(>, <, >=, <=, ==, !=), logical operators (and, or), assignment operator ( = ), membership operators (in, not in), arithmetic-assignment operators (/=, +=, -=, %=, **=, //=).

Punctuators

The structures, statements, and expressions in Python are organized using these symbols known as punctuators. Several punctuators are in python [ ] { } ( ) @ -= += *= //= **== = , etc.

Barebones of a python program

a) Expressions – An expression is a set of operators and operands that together produce a unique value when interpreted.

b) Statements – Which are programming instructions or pieces of code that a Python interpreter can carry out.

c) Comments – Python comments start with the hash symbol # and continue to the end of the line. Comments can be single line comments and multi-line comments.

d) Functions – A function is a block of code that only executes when called. You can supply parameters—data—to a function. As a result, a function may return data.

e) Block or suit – In Python, a set of discrete statements that together form a single code block are referred to as suites. All statements inside a block or suite are indented at the same level.

Variables and Assignments

A symbolic name that serves as a reference or pointer to an object is called a variable in Python. You can use the variable name to refer to an object once it has been assigned to it. However, the object itself still holds the data.
Example
name = “Python”

Dynamic Type vs Static Type

The term “dynamic typing” refers to a variable’s type only being established during runtime. Whereas the statically type done at compile time in a python. Statically type of a variable cannot be change.

Multiple Assignments

Values are assigned by Python from right to left. You can assign numerous variables simultaneously in a single line of code using multiple assignment.
a) Assigning same value to multiple variables
n3 = n2 = n1 = 20
b) Assigning multiple values to multiple variables
n1, n2, n3 = 10, 20, 30

Simple input and output

Input 

Python automatically treats every input as a string input. To convert it to any other data type, we must explicitly convert the input. For this, we must utilize the int() and float() methods to convert the input to an int or a float, respectively.
example
name = input(‘What is your name’)
age = int(input(‘What is your age’)

Output

The print() method in Python allows users to display output on the screen. print statement automatically converts the items to strings.
example
num = 10
print(“Number is “)
print(num) # auto converted to string
print(34) # auto converted to string

Data Type

The classification or categorizing of data elements is known as data types. It represents the type of value that specifies the operations that can be carried out on a given set of data. In Python programming, everything is an object, hence variables and data types are both instances or objects.

Python has following data types by default.

Data types for Numbers

a) Integer – The integers represent by “int”. It contains positive or negative values.
b) Boolean – The boolean type store on True or False, behave like the value 0 and 1.
c) Floating – It is a real number with specified with decimal point.
d) Complex – Complex class is a representation of a complex number (real part) + (imaginary part)j. For example – 2+3j.

Data types for String

Strings in Python are collections of Unicode characters. A single, double, or triple quote are used to store string. There is no character data type in Python.
Example
name = ‘Computer Science’
name1 = “Computer Science’
name2 = ”’Computer Science”’

Lists

Lists are similar to arrays, it is a collections of data in an ordered way. list’s items don’t have to be of the same type in python.
Example
my_list = [1, 2, 3]
my_list1 = [“Computer”, “Science”, “Python”]
my_list2 = [“Computer Science”, 99]

Tuples

Tuple is similar to lists, It is also an ordered collection of python. The only difference between tuple and list is that tuples can’t be modified after it is created, So, that’s why it is known as immutable.
Example
my_tuple = (1, 2, 3)
my_tuple1 = (“Computer”, “Science”, “Python”)
my_tuple2 = (“Computer Science”, 99)

Dictionaries

In Python, a dictionary is an unordered collection of data values that can be used to store data values like a map. This dictionary can hold only single value as an element, Dictionary holds key:value pair.
Example
my_dict = (1: ‘Computer’, 2: ‘Mathematics’, 3: ‘Biology’)
my_dict = (‘Computer’: 1, ‘Mathematics’: 2, ‘Biology’: 3)

Mutable and Immutable Types

In Python, there are two different types of objects: mutable and immutable. It is possible to change mutable data types after they have been formed, whereas immutable objects cannot be altered once they have been created.

Mutable types

The mutable types are those whose values can be changed in place. Only three types are mutable in python lists, dictionaries and sets.

Immutable types

The immutable types are those that can never change their value in place. In Python, the following types are immutable in python integers, floating point numbers, Booleans, strings, tuples.

Expressions

In Python, an expression is made up of both operators and operands. example of expressions in python are num = num + 3 0, num = num + 40.
Operators in Python are specialised symbols that indicate that a particular type of computation should be carried out. Operands are the values that an operator manipulates. An expression is a collection of operators and operands, such as num = num + 3 0.

Type Casting (Explicit Type Conversion)

Type casting, often known as explicit type conversion, Users change the data type of an object to the required data type via explicit type conversion. To achieve explicit type conversion, we use predefined functions like int(), float(), str(), etc.

Math Library Functions

The Python standard library includes a built-in module called math that offers common mathematical functions.

  • math.ceil() – The ceil() function return the smallest integer.
  • math.sqrt() – The sqrt() function returns the square root of the value.
  • math.exp() – The exp() function returns the natural logarithm reised to the power.
  • math.fabs() – The fabs() function returns the absolute value.
  • math.floor() – The floor() function returns round a number down to the nearest intger.
  • math.log() – The log() function is used to calculate the natural logarithmic value.
  • math.pow() – The pow() function returns base raised to exp power.
  • math.sin() – The sin() function returns sine of a number.
  • math.cos() – The cos() function return the cosine of the value.
  • math.tan() – The tan() function return the tangent of the value.
  • math.degrees() – The degrees() converts angle of value from degrees to radians.

Statement Flow Control

Control flow refers to the sequence in which a program’s code is executed. Conditions, loops, and function calls all play a role in how a Python programme is controlled.
Python has three types of control structures –
a) Sequential – By default mode
b) Selection – Used in decision making like if, swithc etc.
c) Repetition – It is used in looping or repeating a code multiple times

Compound Statement

Compound statements include other statements (or sets of statements), and they modify or direct how those other statements are executed. Compound statements often take up numerous lines, however in some cases, a complete compound statement can fit on a single line.
Example
<compound statement header> :
<indented body containing multiple simple and/ or compound statement>

The IF & IF-ELSE conditionals

When using the if statement in Python, a Boolean expression is evaluated to determine whether it is true or false. If the condition is true, the statement inside the if block is executed. If the condition is false, the statement inside the else block is only executed if you have written the else block; otherwise, nothing happens.
Syntax of IF condition
if <conditional expression> :
     statement
     [statement]

Syntax of IF-ELSE condition
if <conditional expression> :
     statement
     [statement]
else :
     statement
     [statement]

Nested IF statement

One IF function contains one test, with TRUE or FALSE as the two possible results. You can test numerous criteria and expand the number of outcomes by using nested IF functions, which are one IF function inside of another.
Syntax of Nested IF statement
if condition :
     if condition :
          Statement
     else :
          Statement

Looping Statement

In Python, looping statements are used to run a block of statements or code continuously for as many times as the user specifies. Python offers us two different forms of loops for loop and while loop.

The For loop

Python’s for loop is made to go over each element of any sequence, such a list or a string, one by one.
Syntax of FOR loop –
for <variable> in <sequence> :
     statements_to_repeat

The range() based for loop

The range() function allows us to cycle across a set of code a predetermined number of times. The range() function returns a series of numbers and, by default, starts at 0 and increments by 1 before stopping at a predetermined value.
Syntax –
range(stop)
range(start, stop)
range(start, stop, step)

The While loop

A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remain true.
Syntax –
while <logical expression> :
loop-body

JUMP Statemement – break and condinue

Python offers two jump statement – break and continue – to be used within loops to jump out of loop-iterations.

The break Statement

A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement.
Syntax –
break

Example –
a = b = c = 0
for i in range(1, 11) :
     a = int(input(“Enter number 1 :”))
     b = int(input(“Enter number 2 :))
     if b == 0 :
          print(“Division by zero error! Aborting”)
          break
     else
          c=a/b
          print(“Quotient = “, c)
print(“program over!”)

The continue statement

Unlike break statement, the continue statement forces the next iteration of the loop to take place, skipping any code in between.
Syntax –
continue

Loop else statement

Python supports combining the else keyword with both the for and while loops. After the body of the loop, the else block is displayed. After each iteration, the statements in the else block will be carried out. Only when the else block has been run does the programme break from the loop.
Syntax –
for <variable> in <sequence> :
     statement1
     statement2
else :
     statement(s)

while <test condition> :
     statement1
     statement2
else :
     statement(s)

Nested Loops

A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop.
The following is an example of a nested loop :
for i in range(1,6) :
     for j in range(1, i) :
          print(“*”, end =’ ‘)

String in Python

Strings in Python are collections of bytes that represent Unicode characters. A single character in Python is just a string of length 1, since there is no such thing as a character data type. Python stores strings as individual characters in consecutive locations with a two-way index. In Python, single, double, or even triple quotes can be used to store strings.
Example
1. string1 = ‘Welcome’
2. string1 = “Welcome”
3. strong1 = ”’Welcome”’

One important thing about string is that you cannot change the individual letters of a string by assignment because strings are immutable.

Traversing a String

When you traverse a string, you use the subscript to access each element of the string one after the other because all the characters are stored in sequence. You can iterate over a string using a for or while loop.
Example
string1 = “Welcome”
string1[0]=’W’, string1[1]=’e’, string1[2]=’l’, string1[3]=’c’, string1[4]=’o’, string1[5]=’m’, string1[6]=’e’

String Operators

There are various operators that can be used to manipulate strings in multiple ways.

>>String Concatenation Operator +

The + operator create a new string by joining the two operand string.
Example
string1 = “Welcome” + “to my School”

>>String Replication Operator *

The string replication operator, *, repeats a single string as many times as you wish through the integer you supply when just one string and one integer are utilized. With string replication, we can duplicate a single string value an equivalent number of times as an integer.
Example
print(“Hello”*3)

output
print(“Hello”*3)

>>Membership Operators

There are two membership operators for strings. These are “in” and “not in”.

a) in – return True if a character or a substring exists in the given string; False otherwise

Example 
print(“a” in “amit”)

Output
True

b) not in – returns True if a character or a substring does not exist in the given string; False otherwise

Example 
print(“a” not in “amit”)

Output
False

Both membership operators, require that both operands used with them are of string type.

>>Comparison Operators

Operators that compare values and return true or false are known as comparison operators. These are the operators: >,, >=, =, ===, and!==.
Example
a) print(2>3)

Output
False

b) print(2>=3)

Output
False

c) print(2<3)

Output
True

d) print(2<=3)

Output
True

e) print(2==3)

Output
False

f) print(2!=3)

Output
True

String Slices

The term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices. Python involves doing so from start to end in order to create a sub-string from the given text.

Example
string1 = “Welcome”
print(string1[2:5])

Output
lco

String Functions

There are numerous built-in functions and strategies for manipulating strings in Python. The following syntax can be used to apply the string manipulation techniques that are discussed below to strings –
Syntax –
<stringobject>.<method name>()

a) string.capitalize() – Return a copy of the string with its first character capitalized.
Example
print(‘welcome to my school’.capitalize())

Output
Welcome to my school

b) 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. Retruns -1 if sub is not found.
Example
1) string1 = “Welcome to my School”
x = string1.find(“School”)
print(x)

Output
14

2) string1 = “Welcome to my School”
x = string1.find(“my”, 3, 20)
print(x)

Output
11

c) string.isalnum() – Returns True if the characters in the string are alphanumeric (alphabets or numbers) and there is al least on character, False otherwise.
Example
string1 = “Welcome1”
x = string1.isalnum()
print(x)

Output
True

d) string.isalpha() – Returns True if all characters in the string are alphabetc and there is at least one characters, False otherwise.
Example
string1 = “Welcome”
x = string1.isalpha()
print(x)

Output
True

e) string.isdigit() – Returns True if all the characters in the string are digits. There must be at least one digit, otherwise it returns False.
Example
string1 = “3652”
x = string1.isdigit()
print(x)

Output
True

f) string.isspace() – Returns True if there will only one whitespace characters in the string.

Example
string1 = ” “
x = string1.isspace()
print(x)

Output
True

g) string.islower() – Returns True if all cased characters in the string are lowercase. There must be at least one cased character. It returns False otherwise.
Example
string1 = “welcome”
x = string1.islower()
print(x)

Output
True

h) string.isupper() – Test whether all cased characters in the string are uppercase and requires that there be at least one cased character. Returns True if so and False otherwise.
Example
string1 = “WELCOME”
x = string1.isupper()
print(x)

Output
True

i) string.lower() – Returns a copy of the string converted to lowercase.
Example
string1 = “WELCOME”
x = string1.lower()
print(x)

Output
welcome

j) string.upper() – Returns a copy of the string converted to uppercase.
Example
string1 = “welcome”
x = string1.upper()
print(x)

Output
WELCOME

h) string.lstrip([chars]) – Returns a copy of the string with leading characters removed.
Example
string1 = “Welcome”
x = string1.lstrip(‘Wel’)
print(x)

Output
come

i) string.rstrip([chars]) – Return a copy of the string with trailing characters removed.
Example
string1 = “Welcome”
x = string1.rstrip(‘come’)
print(x)

Output
wel

Lists in Python

A list is a common Python data type that may hold a series of values of any type. Square brackets are used to indicate the lists. lists are mutable.
Exmple
a. [] # list with no member, empty list
b. [1, 2, 3] # list of integers
c. [1, 2.5, 3.4, 2] # list of numbers(integers and floating point)
d. [‘a’, ‘b’, ‘c’] # list of characters
e. [‘a’, 1, ‘b’, 3.2, ‘New’] # list of mixed value types
f. [‘One’, ‘Two’, ‘Three’] # list of strings

Create lists

To create a list, put a number of expressions, separated by commas in square brackets.
Example
my_list = []
my_list = [33, 32, 54]

Create Empty list

The empty list is [ ]. you can also create an empty list as –
Example
my_list = list()

Create list from existing sequences

You can also use the built – in list type object to create lists from sequences as per the syntax given below –
Example
my_list = list(“Welcome”)
print(my_list)

Output
[‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]

Creating list from keyboard input

You can use this method for creating lists of single characters or single digits via keyboard input.
Example
my_list = list(input(“Enter you name”))
print(my_list)

Output
Enter you name Welcome
Welcome
[‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]

List vs String

Python defines a string as an organised collection of characters. A list is an ordered sequence of different object kinds, whereas a string is an ordered sequence of letters. This is important to keep in mind.

Difference between lists and string

a. Storage – Lists are stored in memory exactly like strings, except that because some of their objects are larger than others, they store a reference at each index insted of single character as in strings.

b. Mutability – Strings are not mutable, while lists are mutable. You cannot individual elements of a string in place, but lists allow you to do so. That is following statement is fully valid for lists.

List Operations

a. Traversing a list – Traversing a list means accessing and processing each element of it. The for loop makes it easy to traverse or loop over the items in a list, as per following syntax –
Example
my_list = [‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]
for a in my_list :
print(a)

Output
W
e
l
c
o
m
e

Joining lists

The concatenation operator + is used to joins two different lists and return the concatenated list.
Example
my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
print(my_list1 + my_list2)

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

Repeating or Replicating lists

Like strings, you can use * operator to replicate a list specified number of times.
Example
my_list = [1, 2, 3]
print(my_list * 3)

Output
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Slicing the lists

List slicing, like string slices are the sub part of a list extracted out. you can use indexes of list elements to create list slices as per following format –
Example
my_list = [15, 33, 25, 14, 72, 52, 65, 47, 95]
print(my_list[3: -3])

Output
[14, 72, 52]

List manipulation

You can perform various operations on lists like, appending, updating, deleting etc.

Appending elements to a list

You can add items to an existing list. The append() method adds a single item to the end of the list.
Example
my_list = [10, 12, 14]
my_list.append(22)
print(my_list)

Output
[10, 12, 14, 22]

Updating Elements to a list

To update or change an element of the list in place, you just have to assign new value to the element’s index in list as per syntax –
Example
my_list = [10, 12, 14]
my_list[1] = 22
print(my_list)

Output
[10, 22, 14]

Deleting Elements from a list

You can also remove items from lists. The del statement can be used to remove an individual item, or to remove all items identified by a slice.
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
del my_list[2]
print(my_list)

Output
[10, 12, 16, 18, 20, 22]

Making True copy of a list

Assignment with an assignment operator ( = ) on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory (called shallow copy).
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
new_list = list(my_list)
print(new_list)

Output
[10, 12, 14, 16, 18, 20, 22]

The index method

The function returns the index of first matched item from the list.

Example
my_list = [10, 12, 14, 16, 18, 20, 22]
print(my_list.index(14))

Output
2

The extend method

The extend() method is also used for adding multiple elements to a list. The extend() function works as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
new_list = [24, 26, 28, 30]
my_list.extend(new_list)
print(my_list)

Output
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]

The insert method

The insert() function inserts an item at a given position. It is used as per following syntax –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.insert(3, 44)
print(my_list)

Output
[10, 12, 14, 44, 16, 18, 20, 22]

The pop method

The pop() is used to remove the item from the list. It is used as per following syntax –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.pop(3)
print(my_list)

Output
[10, 12, 14, 18, 20, 22]

The remove method

The remove() method removes the first occurrence of given item from the list. It is used as per following format –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.remove(14)
print(my_list)

Output
[10, 12, 16, 18, 20, 22]

The clear method

The 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 –
Example
my_list = [10, 12, 14, 16, 18, 20, 22]
my_list.clear()
print(my_list)

Output
[]

The count method

This function returns the count of the item that you passed as argument. If the given item is not in the list, It will return zero.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
print(my_list.count(12))

Output
2

The reverse method

The reverse() reverses the items of the list. This is done “in place”, it does not create a new list.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
my_list.reverse()
print(my_list)

Output
[22, 12, 18, 16, 14, 12, 10]

The sort method

The sort() function sorts the items of the list, by default in increasing order. This is done “in place”, it does not create new list.
Example
my_list = [10, 12, 14, 16, 18, 12, 22]
my_list.sort()
print(my_list)

Output
[10, 12, 12, 14, 16, 18, 22]

Tuples in Python

The Tuples are depicted through parentheses, round brackets, following are some tuples in Python.
Example
a. () # tuple with no member, empty list
b. (1, ) # tuple with one member
c. (1, 2.5, 3.4, 2) # tuple of numbers(integers and floating point)
d. (‘a’, ‘b’, ‘c’) # tuple of characters
e. (‘a’, 1, ‘b’, 3.2, ‘New’) # tuple of mixed value types
f. (‘One’, ‘Two’, ‘Three’) # tuple of strings

Creating Tuples

To create a tuple, put a number of expressions, separated by commas in parentheses. That is, to create a tuple you can write in the form given below –
Example
my_tuple = tuple(“Welcome”)

Creating Empty Tuple

The empty tuple is (). you can also create an empty tuple as –
my_list = tuple()

Create Single Element Tuple

Making a tuple with a single element is tricky because if you just give a single element in round brackets.
Example
my_tuple = (1)

Creating Tuple from keyboard input

You can use this method of creating tuples of single characters or single digits via keyboard input.
Example
my_tuple = tuple(input(“Enter tuple elements “))
print(my_tuple)

Output
Enter tuple elements Welcome
(‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’)

Difference between Tuples and Lists

Lists are mutable, while tuples are not. A tuple’s elements cannot be changed individually once they are in place, while lists let you do so.

Traversing a Tuple

Accessing and processing each element of a tuple is known as traversing it. It is simple to traverse or loop over the items in a tuple when using the for loop.
Example
my_tuple = (“Welcome”, “to”, “my”, “School”)
for a in my_tuple :
print(a)

Output
Welcome
to
my
School

Joining Tuples

The + operator used to join two different tuples.
Example
my_tuple1 = (1, 2, 3)
my_tuple2 = (4, 5, 6)
print(my_tuple1 + my_tuple2)

Output
(1, 2, 3, 4, 5, 6)

Repeating or Replicating Tuples

Like strings and lists, you can use * operator to replicate a tuple specified number of times.
Example
my_tuple = (1, 2, 3)
print(my_tuple * 3)

Output
(1, 2, 3, 1, 2, 3, 1, 2, 3)

Slicing the tuples

Tuple slices, like list-slices or string slices are the sub part of the tuple extracted out. you can use indexes of tuple elements to create tuple slices as per following format –
Example
my_tuple = (1, 2, 3, 4, 5, 6)
new_tuple = my_tuple[ 2 : -2]
print(new_tuple)

Output
(3, 4)

Tuple Functions and Methods

1. The len() method – This method is used to find the length of the tuple.
Exmaple
my_tuple = (1, 2, 3, 4, 5, 6)
print(len(my_tuple))

Output
6

2. The max() method – This method is used to find the maximum value in the given tuples.
Exmaple
my_tuple = (1, 2, 3, 4, 5, 6)
print(max(my_tuple))

Output
6

3. The min() method – This method is used to find the minimum value in the given tuples.
my_tuple = (1, 2, 3, 4, 5, 6)
print(min(my_tuple))

Output
1

4. The index() method – It returns the index of an existing element of a tuple.
Example
my_tuple = (1, 2, 3, 4, 5, 6)
print(my_tuple.index(4))

Output
3

5. The count() function – The count() function returns the number of count memeber element in the given tuples.
Example
my_tuple = (1, 2, 3, 4, 5, 4)
print(my_tuple.count(4))

Output
2

6. The tuple() method – This method is actually constructor method that can be used to create tuples from different types of values.
Example
my_tuple = tuple(“Welcome”)
print(my_tuple)

Output
(‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’)

Dictionaries in Python

A group of key-value pairs are assembled in dictionaries written in Python. Dictionary elements have the form of key:value pairs that link keys to values, making dictionaries mutable, unordered collections. To create a dictionary, you need to include the key:value pairs in curly braces as per following syntax –
Example
my_dict = {1:”One”, 2:”Two”, 3:”Three”}

Accessing Elements of a Dictionary

In dictionaries, the keys listed in the key are used to access the elements: value pairs according to the syntax displayed below –
Example
my_dict = {1: “One”, 2: “Two”, 3: “Three”}
print(my_dict[2])

Output
Two

Traversing a Dictionary

Accessing and handling each element in a collection is known as traversal. A dictionary’s elements can be easily traversed or repeated over with the help of the for loop.
Example
my_dict = { ‘Gujarat’: ‘Gandhinagar’, ‘Bihar’: ‘Patna’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}
keys = my_dict.keys()
print(keys)

Output
dict_keys([‘Gujarat’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’])

Adding Elements to Dictionary

We can add new elements to a dictionary using assignment operator. But remember the key being added must not exist in dictionary and must be unique.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
my_dict[‘Dept’] = ‘Sales’
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000, ‘Age’: 28, ‘Dept’: ‘Sales’}

Deleting Elements from a Dictionary

There are two different methods are used for deleting elements from a dictionary –
a) To delete the element from the dictionary you can use del command.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
del my_dict[‘Age’]
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000}

b) Another method to delete elements from a dictionary is pop() method.
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
my_dict.pop(‘Age’)
print(my_dict)

Output
{‘Name’: ‘Amit’, ‘Salary’: 30000}

Dictionary Functions and Methods

a. The len() method – This method returns length of the dictionary, the count of elements in the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(len(my_dict))

Output
3

b. The clear() method – The method removes all items from the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.clear())

Output
None

c. The get() method – Using get() method you can get the item with the given key.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.get(‘Name’))

Output
Amit

d. The items() method – This method returns all the items in the dictionary.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.items())

Output
dict_items([(‘Name’, ‘Amit’), (‘Salary’, 30000), (‘Age’, 28)])

e. The key() method – This method returns all of the keys in the dictionary as a sequence of keys.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.keys())

Output
dict_keys([‘Name’, ‘Salary’, ‘Age’])

f. The values() method – The method returns all the values from the dictionary as a sequence.
Example
my_dict = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
print(my_dict.values())

Output
dict_values([‘Amit’, 30000, 28])

g. The update() method – This method merges key:value pairs from the new dictionary into the original dictionary.
Example
emp1 = {‘Name’ : ‘Amit’, ‘Salary’ : 30000, ‘Age’ : 28}
emp2 = {‘Name’ : ‘Rejesh’, ‘Salary’ : 35000, ‘Age’ : 29}
emp1.update(emp2)
print(emp1)

Output
{‘Name’: ‘Rejesh’, ‘Salary’: 35000, ‘Age’: 29}

error: Content is protected !!