Revision Tour - II
Revision Tour - II
Revision Tour - II
Python: String
What is String?
Strings are immutable. It means that the contents of the string cannot be changed after it is
created.
A literal/constant value to a string can be assigned using a single quotes, double quotes or triple
quotes.
>>>mystring
Traversing a string:-
Traversing refers to iterating through the elements of a string, one character at a time. A string
can bee traversed using: for loop or while loop. For Example:
myname =”Amjad”
for ch in myname:
A-m-j-a-d-
myString = “PYTHON”
OUTPUT:
Positive Index 0 1 2 3 4 5
myString ‘P’ ‘Y’ ‘T’ ‘H’ ‘O’ ‘N’
Negative Index -6 -5 -4 -3 -2 -1
>>> str.lstrip("T"
("T")
>>> str='Teach
'Teach India Movement'
>>> str.rstrip("nt"
("nt")
>>> str2='1234'
>>> str2.isdigit
isdigit()
True
S.isalpha() Return True if S contains only >>> 'Click123'.isalpha
isalpha()
alphabets False
>>> 'python'.isalpha
isalpha()
True
S.isalnum() Return True if S contains >>> str1 = 'HelloWorld'
alphabet, digit or mixture of >>> str1.isalnum
isalnum()
both. True
>>> str1 = 'HelloWorld2'
HelloWorld2'
>>> str1.isalnum
isalnum()
True
>>> str1 = 'HelloWorld!!'
>>> str1.isalnum
isalnum()
False
S.find(S1) Return index number of first >>> str1 = 'Hello World! Hello
occurance of S1 otherwise -1 Hello'
>>> str1.find('Hello'
'Hello',10,20)
13
>>> str1.find('Hello'
'Hello',15,25)
19
>>> str1.find('Hello'
'Hello')
0
>> str1.find('Hee'
'Hee')
-1
S.partition ( ) Partitions the given string at the >>> str='The
'The Green Revolution'
first occurrence of the substring >>> str.partition
partition('Rev')
(separator) and returns the ('The Green ', 'Rev',
string partitioned into three 'olution')
>>> str.partition
partition('pe')
parts.
('The Green Revolution', '',
1. Substring before the
'')
separator
>>> str.partition
partition('e')
2. Separator
('Th', 'e', ' Green
3. Substring after the separator Revolution')
If the separator is not found in
the string,
ring, it returns the whole
string itself and two empty
strings
ASSIGNMENT
a) 1 b) 6/4
c) str1 d (1.5)
9 Which of the following will result in an error? str1="python"
a) print(str1[2]) b) str1[1]="x"
c) print(str1[0:9]) d) Both (b) and (c)
10 Which of the following is False?
a) String is immutable.
b) capitalize ()) function in string is used to return a string by converting the whole
given string into uppercase.
c) lower() function in string is used to return a string by converting the whole given
string into lowercase.
d) None of these.
11 What will be the output of below Python code? str1="Information"
print(str1[2:8])
a) format b) formation
c) orma d) ormat
12 What will be the output of below Python code? str1="Aplication"
str2=str1.replace('a','A') print(str2)
a) application b) Application
c) ApplicAtion d) applicAtion
13 What will be the output of below Python code? str1=”power”
str1.upper( ) print(str1)
a) POWER b) Power
c) power d) power
14 Which of the following will give "Simon" as output? If str1="John,Simon,Aryan"
a) print(str1[-7:-12]) b) print(str1[-11:-7])
c) print(str1[-11:-6]) d) print(str1[-7:-11])
In the following questions(15 to 20) , a statement of assertion (A) is followed by a
statement of reason(R) . Make the correct choice as :
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False (or partially True)
(d) A is false( or partially True) but R is True
15 Assertion(A): The position and index of string characters are different.
Reason(R) R) : The positions for string’s characters vary from 1..n , where n is
size of the string . The indices for string’s characters vary from 0 to n-1.
n
16 Assertion(A): Operators + and * can work with numbers as well as strings.
Reason(R) : Unlike numbers , for strings , + means concatenation and * means
replication.
17 Assertion(A):String slices and substrings ,both are extracted subparts of a string.
Reason(R) : String slices and substrings mean the same.
18 Assertion(A):Like numbers, ==,>,< can also compare two strings.
Reason(R) :comparison of python strings takes place in dictionary order by applying
character-by-character
character comparison rules for ASCII/Unicode.
19 Assertion(A):String slices and substrings, despite being subparts of a string , are not
the same.
Reason(R) :While the substring contains a continuous subparts of the string , the
slices may or may not contain continuous subparts of a string.
20 Assertion(A): The individual characters of a string are randomly stored in memory.
Reason(R) :Python strings are stored in memory by storing individual characters in
contiguous memory locations.
ANSWER (1 MARK
MARK- MULTIPLE CHOICE QUESTIONS (MCQ)
1 c 11 a
2 a 12 c
3 c 13 a
4 c 14 c
5 b 15 a
6 c 16 a
7 d 17 c
8 c 18 b
9 b 19 a
10 b 20 d
Python: List
List is an ordered sequence, which is used to store multiple data at the same time. List
contains a sequence of heterogeneous elements. Each element of a list is assigned a number
to its position or index. The first index is 0 (zero), the second index is 1 , the third index is 2 and
so on .
Strings are immutable which means the values provided to them will not change in the
program. Lists are mutable which means the values of list can be changed at any time.
Accessing Lists
To access the list's elements, index number is used.
S = [12,4,66,7,8,97,”computer”,5.5
7,8,97,”computer”,5.5]
>>> S[5]
97
>>>S[-2]
computer
Traversing a List
Traversing a list is a technique to access an individual element of that list.
1. Using for loop for loop is used when you want to traverse each element of a list.
>>> a = [‘p’,’r’,’o’,’g’,’r’,’a’,’m’]
>>> for x in a:
print(x, end = ‘ ‘)
output : p r o g r a m
List Operations
1. Concatenate Lists
List concatenation is the technique of combining two lists . The use of + operator can easily
add the whole of one list to other list .
Syntax:
list = list1 + list2
e.g.
#list1 is list of first five odd inte
integers
>>> list1 = [1,3,5,7,9]
#list2 is list of first five even integers
>>> list2 = [2,4,6,8,10]
#elements of list1 followed by list2
>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
Note: If we try to concatenate a list with elements of some other data type, TypeError occurs.
For Example:
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1
TypeError: can only concatenate list (not "str") to list
2. Replicating List
Elements of the list can be replicated using * operator .
Syntax:
list = list * digit
e.g.
in operator:
The operator displays True if the list contains the given element or the sequence of
elements.
>>> list1 = ['C.Sc.','IP'
'IP','Web App']
>>> 'IP' in list1
True
not in operator:
The not in operator returns True if the element is not present in the list, else it
returns False.
>>> list1 = ['C.Sc.','IP'
'IP','Web App']
>>> 'IP' not in list1
False
4) Slicing
#negative indexes
#elements at index -6,-5,-
-4,-3 are sliced
>>> list1[-6:-2]
then it returns and removes the [10, 20, 30, 50, 60]
>>> list1
[10, 20, 30, 40, 50]
L.remove(Value) Removes the given element from >>> list1 = [10,20,30,40,50,30]
Nested List:
When a list appears as an element of another list, it is called a nested list.
>>> list1 = [1,2,'a','c',[6,7,8],4,9]
,[6,7,8],4,9]
#fifth element of list is also a list
>>> list1[4]
[6, 7, 8]
To access the element of the nested list of list1, we have to specify two indices list1[i][j]. The first
index i will take us to the desired nested list and second index j will take us to the desired element
in that nested list.
>>> list1[4][1]
7
TUPLES
A tuple is an ordered sequence of elements of different data types. Tuple holds a sequence of
heterogeneous elements, it store a fixed set of elements and do not allow changes
Tuple vs List
Elements of a tuple are immutable whereas elements of a list are mutable.
Tuples are declared in parentheses ( ) while lists are declared in square brackets [ ]. Iterating
over the elements of a tuple is faster compared to iterating over a list.
Creating a Tuple
To create a tuple in Python, the elements are kept in parentheses ( ), separated by commas.
a = ( 34 , 76 , 12 , 90 )
b=('s',3,6,'a')
Create a empty tuple
T= ( )
Crerate a tuple with single element
T = 5,
Or
T = (5,)
Method Description
len() Returns the length or the number of >>> tup1 = (10,20,30,40,50)
>>> len(tup1)
elements of the tuple passed as
5
Argument
tuple() Creates an empty tuple if no >>> tup1 = list()
list
DICTIONARY
Dictionary is an unordered collection of data values that store the key : value pair instead of
single value as an element .
Keys of a dictionary must be unique and of immutable data types such as strings, tuples etc.
Dictionaries are also called mapping
mappings or hashes or associative arrays
Creating a Dictionary
To create a dictionary in Python, key value pair is used .
Dictionary is list in curly brackets , inside these curly brackets , keys and values are declared .
Syntax:
dictionary_name = { key1 : valuel , key2 : value2 ... }
Each key is separated from its value by a colon ( :) while each element is separated by
commas.
>>> Employees = { " Abhi " : " Manger " , " Manish " : " Project Manager " , " Aasha " : " Analyst
" , " Deepak " : " Programmer " , " Ishika " : " Tester "}
Traversing a Dictionary
1. Iterate through all keys
for i in Employees:
print(i)
Output:
Abhi
Manish
Aasha
Deepak
Ishika
OUTPUT:
{'Raman': 76, 'Suman': 56, 'Sahil': 34, 'Amit': 85, 'John':77}
False
pop () method will not only delete the item from the dictionary, but also return the deleted
value.
Syntax:
Dictionary.pop(key)
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
'Amit'
>>> dict1.pop('Sahil') # It also returns the deleted value
55
>>> dict1
{'Raman':76, 'Suman': 56, ‘Amit’: 85}
1) len():
It Returns the length or number of key: value pairs of the dictionary passed as the argument
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
'Amit'
>>> len(dict1)
4
2) dict()
It Creates a dictionary from a sequence of key-value pairs
>>>pair1 =[('Raman',76),('Suman'
'Suman',56),('Sahil',55),('Amit'
'Amit',85)]
>>> pair1
[('Raman', 76), (‘Suman’, 56), (‘Sahil’, 55), (‘Amit’, 85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Raman': 76, ‘Suman’: 56, ‘Sahil’: 55, ‘Amit’: 85}
3) keys()
It Returns a list of keys in the dictionary
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
'Amit'
>>> dict1.keys()
dict_keys(['Raman', ‘Suman’, ‘Sahil’, ‘Amit’])
4) values()
5) items()
It Returns a list of tuples (key — value) pair
dict1 = {'Raman': 76, 'Suman'
'Suman': 56, 'Sahil': 55, 'Amit':85}
:85}
>>> dict1.item()
dict_items([( 'Raman', 76), (‘Suman’, 56), (‘Sahil’, 55), (‘Amit’, 85)])
6) get()
It Returns the value corresponding to the key passed as the argument
If the key is not present in the dictionary it will return None
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
'Amit'
>>> dict1.get('Amit')
85
>>> dict1.get('Sohan')
>>>
7) update()
It appends the key-value
value pair of the dictionary passed as the argument to the key-value
key pair of
the given dictionary
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
'Amit'
>>> dict2 = {'Sohan':79,'Geeta'
'Geeta':56}
>>> dict1.update(dict2)
>>> dict1
{'Raman': 76, ‘Suman’: 56, ‘Sahil’: 55, ‘Amit’: 85, 'Sohan': 79,
'Geeta': 56}
>>> dict2
{'Sohan': 79, 'Geeta': 56}
8) clear()
It Deletes or clear all the items of the dictionary
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 34, 'Amit':85}
'Amit'
>>> dict1.clear()
>>> dict1
{ }
9) del()
It Deletes the item with the given key.
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
'Amit'
>>> del (dict1['Suman'])
>>> dict1
{'Raman':76,’Sahil’:55, ‘Amit’: 85}
To delete the dictionary from the memory we write:
del Dict_name
>>> del (dict1)
>>> dict1
NameError: name 'dict1' is not defined
10) pop()
pop () method will not only delete the item from the dictionary, but also return the deleted
value.
Syntax:
Dictionary.pop(key)
>>> dict1 = {'Raman':
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
'Amit'
>>> dict1.pop('Sahil') # It also returns the deleted value
55
>>> dict1
{'Raman':76, 'Suman': 56, ‘Amit’: 85}
11) popitem()
The popitem( ) method removes and returns the last inserted key:value pair from
the dictionary.
Syntax:
Dictionary.popitem()
: 76, 'Suman': 56, 'Sahil': 55, 'Amit':85}
>>> dict1 = {'Raman': 'Amit'
>>> dict1.popitem() # It also returns the deleted value with key
('Amit', 85)
For Example:
dict_value = dict1.values()
() # Create a list of dict’s values
55
85
13) sorted()
print(sorted(dict1.keys()))
(dict1.keys()))
print(sorted(dict1.items()))
(dict1.items()))
OUTPUT:
Sorting By Values:
You can use the values as well.
print(sorted(dict1.values()))
(dict1.values()))
OUTPUT: