Python Revision Tour 2 Class 12 Notes

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

Contents show

Python Revision Tour 2 Class 12 Notes

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}

Leave a Comment

error: Content is protected !!