CHAPTER 2
PYTHON REVISION TOUR II
Computer Science
Class XII
STRINGS IN PYTHON
• Sequence of characters enclosed between quotes
STRINGS IN PYTHON
Strings in Python are stored as individual characters in
contiguous locations, with two way index for each location
Forward Indexing
0 1 2 3 4 5
name P Y T H O N
-6 -5 -4 -3 -2 -1
Backward Indexing
INDEXING & LENGTH
Forward Indexing
0, 1, 2, 3, 4, 5, …, size-1 in the forward direction
Backward Indexing
-1, -2, -3, -4, -5, …, -size in the backward direction
Length of a string len(string)
ITEM ASSIGNMENT NOT SUPPORTED
• Strings are immutable
• Individual characters cannot be changed by assignment
STRING TRAVERSAL
Iterating through the elements of
the string, one character at a time
STRING TRAVERSAL
STRING OPERATORS
(i) String Concatenation Operator +
OUTPUT
OUTPUT
(ii) String Replication Operator *
OUTPUT
OUTPUT
(iii)Membership Operators
in not in
in - returns True if a character or a
substring exists in the given string;
False otherwise
not in - returns True if a character or a
substring does not exist in the given
string; False otherwise
MEMBERSHIP OPERATORS
OUTPUT
True
False
False
True
True
False
(iv) Comparison Operators
• <, <=, >, >=, = =, !=
• Strings are compared on the basis of lexicographical
ordering
• Upper-case letters are considered smaller than
lower-case letters
Characters Ordinal Values
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
COMPARISON OPERATORS
OUTPUT
False
True
False
False
COMPARISON OPERATORS
OUTPUT
True
True
True
False
Determining ASCII/Unicode value of a Single Character
• ord() – returns the ASCII value of a character
• chr() – returns the character corresponding to the ASCII
value
OUTPUT
ord(‘A’) 65
chr(97) ‘a’
chr(65) ‘A’
ord(‘J’) 74
ACCESSING SINGLE ELEMENT OF A STRING
0 1 2 3 4 5
name P Y T H O N
-6 -5 -4 -3 -2 -1
name[0] = ‘P’ name[-6] = ‘P’
name[1] = ‘Y’ name[-5] = ‘Y’
name[2] = ‘T’ name[-4] = ‘T’
name[3] = ‘H’ name[-3] = ‘H’
name[4] = ‘O’ name[-2] = ‘O’
name[5] = ‘N’ name[-1] = ‘N’
ACCESSING MULTIPLE ELEMENTS OF A STRING
0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1
0 1 2 3 4 5
s C o mp u t e r S c i e n c e
-16 -15 -14 -13 -12 - -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
11
print(s[0])
print(s[1:4])
print(s[-10:-3])
print(s[2:])
print(s)
STRING SLICING
• String slice refers to a part of the string
• Strings are sliced using the range of indices
str=“Prayer is LIFE”
print(str[3:12])
Start Stop
P r a y e r i s L I F E
0 1 2 3 4 5 6 7 8 9 10 11 12 13
OUTPUT
print(str[3:12]) yer is LI
STRING SLICING
P r a y e r i s L I F E
0 1 2 3 4 5 6 7 8 9 10 11 12 13
str=“Prayer is LIFE”
print(str[:8]) Prayer i
O
print(str[-8:-3]) U is L
T
print(str[5:]) P r is LIFE
U
print(str[:4]+str[4:]) T
Prayer is LIFE
print(str[:-8]+str[-8:]) Prayer is LIFE
STRING SLICING
str=“Prayer”
P r a y e r
0 1 2 3 4 5
OUTPUT
print(str[8])
print(str[3:9])
print(str[6:11]) Empty String
STRING REVERSE
str=“Prayer”
P r a y e r
0 1 2 3 4 5
String [ : : -1 ] Reverses a string
STRING FUNCTIONS
(i) The len() function:
(i) len( ) Returns the number of characters
Syntax: len(<string>)
(ii) The capitalize() function:
(ii) [Link]() Capitalizes the first character
Syntax: <stringObject>.<method name>()
(iii) The count() method:
Returns the number of occurrences of the substring sub in string
<string>.count(sub[,start[,end] ])
(iv) The find() method:
<string>.find(sub[,start[,end] ])
• Returns the lowest index in the
string where the substring sub
is found within the range.
• Returns -1 if sub not found
(v) The index() method:
<string>.index(sub[,start[,end] ])
• Returns the lowest index where the specified substring is found.
• ValueError exception is raised when the substring is not found
(vi) The isalnum() method: <string>.isalnum()
• Returns True if the characters in the string are alphanumeric and
there is at least one character
• Returns False otherwise
(vii) The isalpha() method: <string>.isalpha()
• Returns True if all characters in the string are alphabetic and
there is at least one character
• Returns False otherwise
(viii) The isdigit() method: <string>.isdigit()
• Returns True if all characters in the string are digits and there is at
least one digit
• Returns False otherwise
(ix) The islower() method: <string>.islower()
• Returns True if all cased characters in the string are lowercase
and there must be at least one cased character
• Returns False otherwise
(x) The isspace() method: <string>.isspace()
• Returns True if there is only whitespace characters in the string
and there must be at least one character
• Returns False otherwise
(xi) The isupper() method: <string>.isupper()
• Returns True if all cased characters in the string are uppercase
and there must be at least one cased character
• Returns False otherwise
(xii) The lower() method: (xiii) The upper() method:
<string>.lower() <string>.upper()
• Returns a copy of the string • Returns a copy of the string
converted to lower case converted to upper case
(xiv) The lstrip(), rstrip(), strip() methods:
<str>.lstrip([chars])
• Returns a copy of the string with leading
characters/whitespaces removed
<str>.rstrip([chars])
• Returns a copy of the string with trialing
characters/whitespaces removed
<str>.strip([chars])
• Returns a copy of the string with leading and
trialing characters/whitespaces removed
(xv) The startswith(), endswith() methods:
<str>.startswith(prefix[start[,end]])
• Returns True if <str> starts with the argument prefix,
otherwise returns False
• Returns False otherwise
<str>.endswith(prefix[start[,end]])
• Returns True if <str> ends with the argument suffix, otherwise
returns False
• Returns False otherwise
(xvi) The title() method:
[Link]()
• Returns the string with first cased character of every word in the
string in uppercase and rest in lowercase
(xvii) The istitle() method:
<string>.istitle()
• Returns True if the string has a Title case
• False otherwise
(xviii) The replace() method:
<string>.replace(old,new)
• Returns a copy of the string with all occurrences of substring old
replaced by new string
(xix) The join() method:
<string>.join(<string iterable>)
• Joins a string or character after each member of the string iterator
(i) If the string based iterator is a string, then <str> is inserted after
every character of the string.
(ii) If the string based iterator is a list or tuple of strings, then the
given string/character is joined with each member of the list or
tuple. But the tuple or list must contain only strings.
(xx) The split() method:
<string>.split(<string/char>)
• Splits a string based on given string or character
• Returns a list containing split strings as members
(xxi) The partition() method:
<str>.partition(<sep/str>)
• Returns a 3-tule
→ part before the separator
→ the separator itself
→ the part after the separator
• If the separator is not found, it returns a 3-tuple containing the
string itself, followed by two empty strings.
<str>.partition(<sep/str>)
(xxi) The swapcase() method: <str>.swapcase()
• Returns a copy of the string <str> with uppercase characters
converted to lowercase and viceversa
Lists in Python
• List stores a sequence of values of any data type
• The lists are depicted through square brackets
Empty Lists
The empty list is []
Two ways of
creating empty list
Long Lists
List contain many elements
Nested Lists
List having list itself as an element
Creating Lists from keyboard
Creating Lists from Existing Sequence
L=list(<sequence>)
INDEXING & LENGTH
Forward Indexing
0, 1, 2, 3, 4, 5, …, size-1 in the forward direction
Backward Indexing
-1, -2, -3, -4, -5, …, -size in the backward
direction
Length of a list len(list)
Similarities between Strings & Lists
len
Slicing Indexing
Accessing elements
Membership Operators
Concatenation
Replication
Differences between Strings & Lists
Mutability Storage
Mutability
Storage
ACCESSING SINGLE ELEMENT OF A LIST
Forward Indexing
0 1 2 3 4 5
L1 C H E R R Y
-6 -5 -4 -3 -2 -1 Backward Indexing
List Traversal
Accessing and processing
each element of the list
Membership Operators
in not in
Comparing Lists
Lists can be compared using standard
comparison operators <, >, <=, >=, ==, !=
List Operations
(i) Joining Lists
Concatenation Operator +
OUTPUT
When += is used with lists then it requires the operand on
the right to be an iterable and it will add each element of
the iterable to the list.
(ii) Replicating Lists
Replication Operator *
(iii) Slicing the Lists
0 1 2 3 4 5 6 7
L= [‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
-8 -7 -6 -5 -4 -3 -2 -1
print(L[1:4])
print(L[2:])
print(L[-7:-3])
Assigning new values to list slice
Making True Copy of a List
Assignment makes the two variables point to the
one list in memory (shallow copy)
Creating independent list identical to another list
(deep copy)
Creating the true copy of a list by using copy() method
List Functions and Methods
(i) The len() function
Returns the length of the argumrnt/list
Syntax
len(<list>)
(ii) The list() method
Returns a list created from the passed argument of
sequence(string, list, tuple, etc.). If no argument is
passed, creates an empty list
Syntax list([<sequence]>)
3. The index method
[Link](<item>)
Returns the index of first matched item from the list
4. The append method
[Link](<item>)
Adds an item at the end of the list
Does not return the new list, just modifies the original
5. The extend method
[Link](<list>) Adds multiple elements to a list
append() adds one element to a list, extend() add multiple elements from a list
6. The insert method
[Link](<Ind>,<item>)
Inserts an item at a given position
7. The pop method
[Link](<index>)
• Removes an element from the given position in
the list and return it
• If no index is specified, removes and returns the
last element in the list
Last element is
removed
Element at 4th index is removed
8. The remove method
[Link](<value>)
Removes the first occurrence of given item from the list
9. The clear method
[Link]()
Removes all the items from the list
10. The count method
[Link](<item>)
Returns the count of the item that is
passed as argument
11. The reverse method
[Link]()
Reverses the items of the list
12. The sort method
[Link]() Sorts the items of the list , by default in increasing order
13. The sorted() method
sorted(<iterable_sequence>,[reverse=False])
Returns a new sorted list with sorted elements in it.
14. Delete Remove items from list
Syntax del List[<index>]
Syntax del List[<start>:<stop>]
Syntax del List
15. The max & min method
Returns the item with
max(List) maximum value in the list
Returns the item with
min(List) minimum value in the list
Tuples in Python
• Tuple stores a sequence of values of any data type
• The tuples are depicted through parantheses
• Tuples are immutable sequences of Python
Creating Tuples
(1) The Empty Tuple
The empty tuple is ( )
Two ways of creating
empty tuple
(2) Single Element Tuple
Add a comma after the single element
Stores an integer value not a tuple
(3) Long Tuples
A tuple containing many elements
(4) Nested Tuples
A tuple containing another tuple in it as a member is called a nested list
Creating Tuples from existing sequence
L=tuple(<sequence>)
Creating Tuple from keyboard
INDEXING & LENGTH
Forward Indexing
0, 1, 2, 3, 4, 5, …, size-1 in the forward direction
Backward Indexing
-1, -2, -3, -4, -5, …, -size in the backward direction
Length of a tuple len(tuple)
Accessing individual element of Tuple
Forward Indexing
0 1 2 3 4 5
T1 I P H O N E
-6 -5 -4 -3 -2 -1 Backward Indexing
T1[0] = ‘I’ T1[-6] = ‘I’
T1[1] = ‘P’ T1[-5] = ‘P’
T1[2] = ‘H’ T1[-4] = ‘H’
T1[3] = ‘O’ T1[-3] = ‘O’
T1[4] = ‘N’ T1[-2] = ‘N’
T1[5] = ‘E’ T1[-1] = ‘E’
Accessing Tuple Elements / Slicing
0 1 2 3 4 5 6 7
T= (‘M’, ‘a’, ‘l’, ‘a’, ‘y’, ‘s’, ‘i’, ‘a’)
-8 -7 -6 -5 -4 -3 -2 -1
print(T) (‘M’, ‘a’, ‘l’, ‘a’, ‘y’, ‘s’, ‘i’, ‘a’)
print(T[0]) ‘M’
print(T[1:4]) (‘a’, ‘l’, ‘a’)
print(T[2:]) (‘l’, ‘a’, ‘y’, ‘s’, ‘i’, ‘a’)
print(T[-7:-3]) (‘a’, ‘l’, ‘a’, ‘y’)
Similarities between Tuples, Lists & Strings
len
Slicing Indexing
Accessing elements
Membership Operators
Concatenation
Replication
Differences between Tuples & Lists
Mutability
Traversing a Tuple
Accessing and processing each element of the tuple
Tuple Operations
Joining Tuples
Concatenation Operator +
T1=(1,2,3) OUTPUT
T2=(4,5,6) (1,2,3,4,5,6)
print(T1+T2)
Replication Operator *
T= (1,2,3) OUTPUT
(1,2,3,1,2,3,1,2,3)
print(T*3)
Slicing the Tuples
0 1 2 3 4 5 6 7
T= (‘M’, ‘a’, ‘l’, ‘a’, ‘y’, ‘s’, ‘i’, ‘a’)
-8 -7 -6 -5 -4 -3 -2 -1
print(T) (‘M’, ‘a’, ‘l’, ‘a’, ‘y’, ‘s’, ‘i’, ‘a’)
print(T[0]) ‘M’
print(T[1:4]) (‘a’, ‘l’, ‘a’)
print(T[2:]) (‘l’, ‘a’, ‘y’, ‘s’, ‘i’, ‘a’)
print(T[-7:-3]) (‘a’, ‘l’, ‘a’, ‘y’)
Membership Operators
in not in
T= (8,4,2,3,1,5) OUTPUT
print(1 in T) True
OUTPUT
T= (8,4,2,3,1,5)
print(1 not in T) False
Comparing Tuples
Packing/Unpacking Tuples
• Creating a tuple from a set of values is called packing
• Creating individual values from a tuple’s elements is called unpacking
<var1>,<var2>,<var3>,…=t
Packing
Unpacking
Deleting Tuples
The del statement of Python is used to delete elements and objects.
Tuples Functions and Methods
(i) len() method Returns the length of the tuple
Syntax
len(tuple>)
(ii) max() function
Returns the element from the tuple having maximum value
Syntax
max()
max(<tuple>)
90
(iii) min() function
Returns the element from the tuple having minimum value
Syntax
min()
200 min(<tuple>)
(iv) sum() function
Returns the sum of the elements of the tuple.
(Numeric elements)
Syntax sum(<tuple>)
(v) index() method
Returns the index of an existing element of a tuple
Syntax <tuple>.index(<item>)
(vi) The count() method
Returns the count of the item that is passed as argument
Syntax <tuple>.count(<item>)
(vii) The sorted() function
Returns a new sorted list with sorted elements in it.
Syntax: sorted(<iterable sequence>,[reverse=False])
(viii) The tuple() method
Constructor method to create tuples from different types of values
Syntax: tuple(<sequence>)
➢ Creating empty tuple
➢ Creating tuple from a list
➢ Creating a tuple from a string
➢ Creating a tuple from keys of a dictionary
Indirectly Modifying Tuples
➢ Using Tuple Unpacking
First unpack the tuple
Redefine or change the value
Repack the tuple
➢ Using the constructor functions of lists and tuples
Convert tuple to list
Redefine or change the value
Create a tuple
Dictionaries in Python
• Collection of key-value pairs separated by commas
• Mutable, unordered collections that associate keys to values
• Dictionaries are enclosed within curly brackets
Creating Dictionaries
SYNTAX:
<dictionary-name>={<key>:<value>, <key>:<value>, <key>:<value>,…}
The keys of the dictionary must be of immutable types. (String, Tuple, Number)
Accessing Elements of a Dictionary
• Elements are accessed through the keys defined in the key : value pairs
<dictionary-name> [<keys>]
Traversing a Dictionary
Accessing and processing each element of the dictionary
Accessing Keys or Values simultaneously
<dictionary>.keys()
<dictionary>.values()
Characteristics of a Dictionary
❑ Unordered set of key : value pairs
❑ Not a sequence because it is an unordered set of elements
❑ Dictionaries are indexed by Keys
❑ Keys must be of any non-mutable type
❑ Each of the keys must be unique
❑ Dictionaries are also mutable.
❑ Internally stored as mappings
<dictionary>[<key>] = value
Multiple ways of creating Dictionaries
1. Initializing a Dictionary
2. To create Empty Dictionary
Two ways to create an empty dictionary.
1. Empty curly braces
2. dict()
3. Adding key : value Pairs to an Empty Dictionary
4. Creating a Dictionary from name and value pairs
(i) Specific Key:Value pairs as keyword arguments to dict()
function – (Keys as arguments, enclosed within paranthesis)
(ii) Specify comma-separated Key:Value pairs– Enclose
within curly brackets inside paranthesis
(iii) Specify keys separately and corresponding values
separately
(iv) Specify Key : Value pair separately in form of sequences
Adding Elements to Dictionary
<dictionary>[<key>] = <value>
Write a program to add new student’s roll numbers and marks in the
dictionary D created with roll numbers as the keys and marks as the values
Nesting Dictionaries
Storing a dictionary inside another dictionary
Updating Existing Elements in a Dictionary
<dictionary>[<key>] = <value>
Deleting Elements from a Dictionary
del<dictionary>[<key>]
Deleting Elements from a Dictionary
(i) Using del
(ii) Using pop() method
<dictionary>.pop(<key>,<value>)
(iii) The popitem() method
Removes the (key:value) pairs in LIFO order
<dictionary>.popitem( )
(iv) The clear() method
Removes all items from the dictionary
<dictionary>.clear( )
Dictionary Operations
Checking for existence of a Key
in not in
Pretty printing a Dictionary
Used to make it more readable and presentable
import json module and then use dumps() function
Dictionary Functions and Methods
1. The len function
len(<dictionary>)
2. The clear() method
Removes all the items from the dictionary
<dictionary>.clear()
3. The get() method
Can get the item with the given key from the dictionary
<dictionary>.get(key,[default])
4. The items() method
Returns all of the items in the dictionary as a sequence of (key, value) tuples
<dictionary>.items()
5. The keys() method
Returns all of the items in the dictionary as a sequence of keys
<dictionary>.keys()
6. The values() method
Returns all the values from the dictionary as a sequence (a list)
<dictionary>.values()
7. The fromkey() method
Used to create a new dictionary from a sequence containing all the keys and a
common value, which will be assigned to all the keys.
[Link](<keysequnce>,[<value>])
8. Extend/Update Dictionary with new key:value pairs
(i) The setdefault() method
• If the key is not already present in the dictionary, it
will add the specified new key:value pair to the
dictionary and return the value of the added key
• If the given key is already present in the dictionary,
the dictionary will not be updated, but the current
value associated to the specified key is returned
(i) The setdefault() method
8. The update() method
Merges key : value pairs from the new dictionary into the original dictionary, adding
or replacing as needed
<dictionary>.update(<other-dict>)
9. The sorted() function
Sorts the keys of the dictionary and returns a sorted list.
sorted(<dict>,[reverse=False])
9. max(), min() and sum() function
Works with the keys of the dictionary and the keys must be of homogeneous types.
max(<dict>) min(<dict>) sum(<dict>)
Shallow Copy
Refers to a copy of a dictionary where only a copy of the keys is created.
<dict>.copy()
Working of copy()
Does not create a copy
Case 1: Creating copy using assignment operator internally, rather, it
make two labels (like
aliases) reference the
<dict>=<dict1> same dictionary.
Working of copy()
Creates a copy of keys
Case 2: Creating a copy using the copy() method. with the new name and
(i) If the VALUES referenced by the keys are immutable the values referenced
are shared by the two
copies.
<dict>.copy()
(i) If the VALUES referenced by the keys are immutable -
Changes made in the copy created with copy() will not be
reflected in the original dictionary
(ii) If the VALUES referenced by the keys are MUTABLE - Keys
will be referring to the same Python objects (same memory
address)
JINI N K