0% found this document useful (0 votes)
3 views128 pages

STD-12th - Chapter -2 Python Revision Tour-2

Chapter 2 of the document provides a revision of Python concepts, focusing on strings, lists, tuples, and dictionaries. It covers string characteristics, including immutability, slicing, and various string operators, as well as list creation and operations. The chapter serves as a refresher for students to enhance their understanding of these fundamental data structures in Python.

Uploaded by

solankikshitij70
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views128 pages

STD-12th - Chapter -2 Python Revision Tour-2

Chapter 2 of the document provides a revision of Python concepts, focusing on strings, lists, tuples, and dictionaries. It covers string characteristics, including immutability, slicing, and various string operators, as well as list creation and operations. The chapter serves as a refresher for students to enhance their understanding of these fundamental data structures in Python.

Uploaded by

solankikshitij70
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

Chapter -2

Python Revision tour


II

STD-12th
INDEX
2.1 Introduction

2.2 Strings in Python

2.3 Lists in Python

2.4 Tuples in Python

2.5 Dictionaries in Python

2.6 Sorting Techniques

2
2.1 Introduction

 The previous chapter — Python Revision Tour I — covered basic concepts like : Python
basics, Data handling, and control flow statements.

 This chapter is going to help you recall and brush up concepts


like Strings, Lists, Tuples and Dictionaries.

3
2.2 STRINGS IN PYTHON
2.2 STRINGS IN PYTHON
 Strings in Python are stored as individual characters in contiguous(neighbour) locations,
with two-way index for each location. Example: a=“GREEN VALLEY”

BACKWARD INDEX -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1


G R E E N V A L L E Y
FORWARD INDEX 0 1 2 3 4 5 6 7 8 9 10 11

5
2.2 STRINGS IN PYTHON
 Strings in Python are stored by storing each character separately in
contiguous(neighbour) locations

 The characters of the strings are given two-way indices :

 0, 1, 2, size-1 in the forward direction and -size in the backward direction.

6
2.2 STRINGS IN PYTHON
 Length of string variable can be determined using function len(<string>), i.e., to
determine length of above shown string name, you may write :

Example: len(msg)

7
2.2.1 Item Assignment not Supported
 In Python strings is that you cannot change the individual letters of a string by
assignment because strings are immutable and hence item assignment is not supported,
i.e.,

8
2.2.2 Traversing a String
 Traversing refers to iterating (repeating) through the elements of a string, one character
at a time.

 To traverse through a string, you can write a loop like :

9
1.2.3 Tokens in Python – Operators
 Operators are tokens that trigger some computation / action when applied to
variables and other objects in an expression.
 The operators can be

 Arithmetic operators ( +, -, *, /, %, **, // )  Logical operators ( and, or )

 Bitwise operators ( &, ^, | )  Assignment operator ( = )

 Shift operators ( <<, >> )  String operator (+, *) (Lesson-2)

 Identity operators ( is, is not )  Membership operators ( in, not in )

 Relational operators ( >, <, >=, <=, ==, != )  Arithmetic-Assignment operators


( /=, +=, -=, */, %=, **=, //=)

11
2.2.3 String Operators
 In this section, you'll be learning to work with various operators that can be used to
manipulate strings in multiple ways.

 String Concatenation Operator +

 String Replication Operator *

 String Membership operator (in & not in)

 String Comparison/Relational operators ( >, <, >=, <=, ==, != )

12
2.2.3 String Operators - String Concatenation Operator +

 String concatenation means joining two strings or joining characters one after another.

 The plus (+) operator is used to perform string concatenation.

Example: one string stores “power" and another string stores “full".

When you perform concatenation as: “power" + “full", it returns “powerfull".

13
2.2.3 String Operators - String Concatenation Operator +
 The + operator has to have both operands of the
same type either of number types (for addition) or of string types (for multiplication).

 It cannot work with one operand as string and one as a number.

14
2.2.3 String Operators - String Replication Operator *
 A string or characters can be repeated a specific number of times using the repetition
operator (*).

 The repetition operator makes multiple copies of a sequence and joins them all
together.

 The repetition (*) operator is called the multiplication operator, which is used to
multiply two numeric values and display the result.

Example: 'welcome*3=welcomewelcomewelcome’

15
2.2.3 String Operators - String Replication Operator *
 The * operator has to either have both operands of the
number types (for multiplication) or one string type and one number type (for replication).

 It cannot work with both operands of string types.

16
2.2.3 String Operators - String Membership Operators
 Membership operators are used to test the presence of an element in a string. There
are two types of membership operators as discussed below:

 'in' operator: The membership operator 'in' is used to check if a value exists in a
sequence or not. If it finds the element in the sequence, then it returns True, otherwise
it returns False.

 'not in' operator: The 'not in' operator returns True if it does not find the element in the
sequence, otherwise it returns false.

17
2.2.3 String Operators - String Membership Operators
N

18
2.2.3 String Operators - String Comparison Operators
 Python's standard comparison operators i.e., all relational operators ( >, <, >=, <=, ==,
!= ) apply to strings also.

 The comparisons using these operators are based on the


standard character-by-character comparison rules for ASCII or Unicode (i.e., dictionary
order).

19
2.2.3 String Operators - String Comparison Operators
 String comparison principles are :

 Strings are compared on the basis of lexicographical ordering (ordering in dictionary)•

 Upper-case letters are considered smaller than the lower-case letters.

20
Determining ASCII/Unicode Value of a Single Character
 The Python offers a built-in function ord( ) that takes a single character and returns
value to the corresponding ASCII value or Unicode value.

Opposite of ord() function is chr() function

 The Python offers a built-in function chr( ) takes a value in integer form and returns the
character corresponding to that ASCII value or Unicode value.

21
2.2.4 String Slices
 A slice means "a part of" something.

 Similarly, Python allows you to fetch a substring from a string.


-6 -5 -4 -3 -2 -1
 The substring or a part of the string can be accessed by using the
H o n e s t
slicing operator colon (:).
0 1 2 3 4 5

 An expression of the form S[start:stop] returns the substring or a part


of the string S starting with index start, and displays up to Stop-1

22
2.2.4 String Slices
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

G R E E N V A L L E Y
0 1 2 3 4 5 6 7 8 9 10 11

23
2.2.4 String Slices with help of increment
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

G R E E N V A L L E Y
0 1 2 3 4 5 6 7 8 9 10 11

24
2.2.4 String Slices with help of decrement
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

G R E E N V A L L E Y
0 1 2 3 4 5 6 7 8 9 10 11

25
2.2.4 String Slices with Interesting Inference
 Using the same string slicing technique, you will find that

for any index n, s[:n] + sl[n:] will give you original string s.

 This works even for n negative or out of bounds.

26
2.2.4 String Slices with Interesting Inference
 Using the same string slicing technique, you will find that

for any index n, s[:n] + sl[n:] will give you original string s.

 This works even for n negative or out of bounds.

27
2.2.5 String Functions
 Python also offers many built-in functions and methods for string manipulation.

 The string manipulation methods that are being discussed below can be applied to
strings as per following

SYNTAX <StringObject>.<method name> ( )

28
2.2.5 String Functions

29
2.2.5 String Functions

-30 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

i t g o e s a s - r i n g a r i n g a r o s e s

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

30
2.2.5 String Functions

-30 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

i t g o e s a s - r i n g a r i n g a r o s e s

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

31
2.2.5 String Functions

32
2.2.5 String Functions

33
2.2.5 String Functions

title( ) Syntax: Str. title( )

Here words start with an


uppercase character and the remaining characters
are lowercase. 34
2.2.5 String Functions

35
2.2.5 String Functions

36
2.2.5 String Functions

If we give space and also tells to remove left starting character “W”
Both condition will not work that is space and to remove

If we not give space and tells to remove left starting character “W” – It will work

37
2.2.5 String Functions

If we not give space and tells to remove left but not starting character “W”
– It will not work

38
2.2.5 String Functions

39
2.2.5 String Functions

If we give space and also tells to remove right last character “n”
Both condition will not work that is space and to remove

If we not give space and tells to remove right last character “n” – It will work

40
2.2.5 String Functions

If we not give space and tells to remove right side but not last
character “o” It will not work

41
2.2.5 String Functions

42
2.2.5 String Functions

If we give space and also tells to remove character “Welcome”


Both condition will not work that is space and to remove

TO remove any character -


It should be first character or last character then
only it will work
Otherwise not

43
2.2.5 String Functions

44
2.2.5 String Functions

Concatenation Operator

45
2.2.5 String Functions

46
2.2.5 String Functions

47
2.2.5 String Functions

48
2.2.5 String Functions

swapcase( ) Syntax: Str. swapcase( )

It returns a copy of the string <Str> with


uppercase characters converted to lowercase and
vice versa.

49
2.3 List
 A list is a standard data tvpe of Python that can store a sequence of values belonging
to any type. The Lists are depicted through brackets

 These data elements can be of the same data type or they can be of different data types also.

 The items in the list are separated by the comma (,) and enclosed within the square brackets [ ].

50
1.6 Data Types / Core (Main) Data Types - Sequence

 List: Lists in Python contain items of different data types & it is mutable that is
changeable one can change / add / delete a list’s elements. .

 The items stored in the list are separated by a comma (,) and are enclosed using
square brackets [ ].

 A list stores elements in a sequence from Zero(0), one after another….1,2,3….so ..on.

51
2.3. List Operations

52
2.3.3 List Operations
Creating Lists from Existing Sequences

 You can also use the built-in list type object to create lists from sequences as per
the syntax

53
2.3.3 List Operations
Creating Lists from Keyboard input

 You can use this method of creating lists of single characters or single digits
via keyboard input.

54
2.3.3 List Operations

55
2.3.3 List Operations

56
2.3.3 List Operations

57
2.3.3 List Functions

 The index() function returns the index of the given element in the list.

 If the element is not present in the list, then it will give an error.

 The index of an element can be searched by using the start and stop parameters.

 For example, index ('element', start, stop) returns the index value of an item if it

is present between the starting index value and the stop index value.

58
2.3.3 List Functions – index(“element”start,stop)

59
2.3.3 List Functions – index(“element”start,stop)

60
2.3.3 List Functions

 The function append() adds its arguments as a single element at the end of the list.

 append() function takes exactly one element and returns no value

 The append( ) does not return the new list, just modifies the original.

 Values can be numbers, strings or any sequence, which can be appended to the list.

61
2.3.3 List Functions – append()

62
2.3.3 List Functions

 The extend( ) function iterates over its arguments and adds each element to the list

at the end.

 extend() function takes exactly one element (a list type) and returns no value

 The extend( ) does not return the new list, just modifies the original.

 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.

63
2.3.3 List Functions – extend()

64
2.3.3 List Functions – Difference extend() Vs append

65
2.3.3 List Functions

 The insert() function allows you to add an element at a specified position in the list.

 insert(position,element) function takes exactly two arguments and returns no value

 The insert( ) does not return the new list, just modifies the original.

66
2.3.3 List Functions – insert(position,element)

Red sauce salt sugar Cooking oil bread butter curd


0 1 2 3 4 5 6

In Insert() we can give position but in


append() it will enter the value at last

67
2.3.3 List Functions

 The pop() function removes the element at the given index from the list and

returns the removed item.

 pop(index) function takes one arguments and returns a item being deleted.

 If no index specified, pop( ) removes and returns the last item in the list.

 The pop() function also takes negative index and removes items from the list.

68
2.3.3 List Functions – pop(index)

Example 3

69
2.3.3 List Functions

 The remove() method removes the first matching element that has been provided as

the function argument from the list.

 remove(item/value name) function takes one arguments and doesn't return anything

 If no item/value name specified, remove( ) function will shows an error.

70
2.3.3 List Functions – remove(value)

71
2.3.3 List Functions
 The count() function returns the total number of elements with the specified value
provided in argument.

 count(item/value name) function takes one arguments and return numbers of value/item

 If the given item is not in the list, it returns zero.

72
2.3.3 List Functions

 The clear() function removes all the items from the list and the list becomes empty list
after this function. This function returns nothing.

 clear() function takes no argument and doesn't return anything.

73
2.3.3 List Functions
 The function reverse() is used to reverse
the elements of the list.

 It reverses the sequence of the elements in


the list and updates the original list.

 reverse() function takes no argument and


doesn't return anything.

74
2.3.3 List Functions
 The sort() function arranges the elements of a given list either in an ascending or
descending order.

 It changes the list and does not return any value.

75
2.3.3 List Functions – sort()

76
2.3.3 List Functions
 The sorted() function sorts the elements of a given sequence in a specific order,
either ascending or descending and returns the sorted list.

Sort(variable name)
Sort(variable name, reverse=True)

 It doesn't changes the list and sorted list.

77
2.3.3 List Functions – sorted()

78
79
2.3.4 List Manipulation
 We can perform various operation on list like adding, deleting, updating etc.

 For Adding element in a list, we use append() function or extend() function or


insert() function etc.

 For Deleting element from list, we use del statement, pop function, remove function,
clear function etc.

80
2.3.4 List Manipulation – Delete – del statement
 For Deleting element from list, we use
del statement, pop function, remove
function, clear function etc.

 The del statement can be used to


remove an individual item or to
remove all items identified by a Slice.

 If you use del list_name, it will delete


all the elements and the list object.
After this, no object by the name
list_name would be existing. 81
2.3.4 List Manipulation – Update

 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.

82
2.3 Similarity between List Vs String
Function
Description List String
Name
Function Length returns
the number of items
Len(L)
(count) in the list or
string

It returns the item at


index i
L[i]
(the first item has index
0)

Slicing returns a new


L[i:j] list, containing the
objects between i and j. 83
2.3 Similarity between List Vs String
Function Name Description List String

Membership 'in' and


Operator 'not in'

Concatenation
operator +
84
2.3 Similarity between List Vs String
Function Name Description List String

Replication
Operator *

Accessing Variable
Individual name
Elements [index]
85
2.3 Difference between List Vs String

MUTABILITY Strings are immutable, whereas lists are mutable.

Strings can only store character data,


DATATYPE whereas in lists you can store different types of data.
Strings store the characters in their consecutive
locations,
STORAGE whereas the list stores the references to
their elements.

86
2.4 Tuples in Python

 The Tuples are depicted through parentheses i.e. round brackets, e.g., following are
some tuples in Python :

 Tuples are immutable sequences i.e., you cannot change elements o a tuple in place.

87
2.4. Creating Tuples

Tuple Display
Construct

88
2.4. Creating Tuples
Creating tuples from Existing Sequences

 You can also use the built-in list type object to create tuple from sequences as
per the syntax

89
2.4. Creating Tuples
Creating Tuple from Keyboard input

 You can use this method of creating lists of single characters or single digits
via keyboard input.

90
2.4 Tuple Functions

91
2.4 Tuple Operations

92
2.4 Tuple Operations

93
2.4 Tuple Functions

94
95
2.4 Tuple Operations
Unpacking Tuples

 Creating a tuple from a set of values is called packing and its reverse,
i.e., creating values from a tuple's elements is called unpacking.

PACKING

UNPACKING

96
2.3 Similarity between Tuples Vs List Vs String

Function
Description Tuples List String
Name

Function Length
returns the number
Len(L) of items (count) in
the tuple or list or
string

97
Funct
ion
Description Tuples List String
Nam
e

It returns
the item at
index i
L[i]
(the first
item has
index 0)

Slicing
returns a
new tuple
or list,
L[i:j]
containing
the objects
between i
and j. 98
2.3 Similarity between Tuples Vs List Vs String
Function Descripti
Tuples List String
Name on

'in’
Membership and
Operator 'not in'

Concatenation
operator +
99
2.3 Similarity between Tuples Vs List Vs String
Function Descrip
Tuples List String
Name tion

Replication
Operator *

Accessing Variabl
Individual e name
Elements [index]

100
2.4 Similarity between Tuple & List
The list and tuple are similar in the following ways:

 Both are sequence data types that store collection of items or values.

 Both are ordered collection data types.

 Both can store value of any data type. It means the list and tuple can store the values
of string, integer, float, list, and tuple, etc.

 Items or values can be accessed by index value or indexing in both.

 Both can contain duplicate values.

101
2.3 Difference between List Vs Tuple

MUTABILITY Tuples are immutable, whereas lists are mutable.

In Tuple, Operations like insert and delete cannot be


performed on any data type.
OPERATIONS whereas In List, Operations like insert and delete can be
performed on any data type.

UPDATING In Tuple, items of tuple cannot be changed/update once


assigned.
Elements whereas In List, items of a list can be changed/update once
assigned.
102
2.5 Dictionaries in Python
 Dictionary is a data type in Python. It is an unordered collection of items. Each item
of a dictionary has a key-value pair.

 Dictionary is a mutable data type.

 Values in a dictionary can be of any data type and can be duplicated. So, the values
can be added, removed, and changed at any time.

 However, the keys of a dictionary must be unique. They are case-sensitive too. So,
the keys of the dictionaries are immutable.

Key1:value1,
key2:value2

103
2.5 Dictionaries in Python
Creating a Dictionary

 A dictionary can be created by enclosing a comma-separated list of key-value pairs in


curly braces { }.

 A colon (:) separates each key from its associated value.

 Values of a dictionary can be of list, integer, float, string,


or any other data type. They can be repeated, but keys
are unique and immutable type.

104
2.5 Dictionaries in Python
Creating a Empty Dictionary

 An empty dictionary can be created by declaring an identifier with curly brackets.

The dict() function is used to


create a dictionary with or
without key-value pair passed as
an argument.

105
2.5 Dictionaries in Python
Accessing Elements of a Dictionary

 In a list and tuple, the elements can be accessed through indexing.

 However, in a dictionary you can access the elements by referring to their keys, inside
square brackets.

 If you want to access a key does not exist


in the dictionary, then an error will occur.
106
2.5 Dictionaries Operations in Python
Adding Elements of a Dictionary

 You can add new elements (key : value pair) to a dictionary.


<dictionary>[“Key”] = value

 But the key being added must not exist in dictionary and must be unique.

 If the key already exists, then this statement will change the value of existing key and
no new entry will be added to dictionary.

 One value at a time can be added to a dictionary by defining the value along with the
key.

107
2.5 Dictionaries Operations in Python
Updating Existing Elements in a Dictionary

 The value of a key can be modified or changed by using an assignment operator.

108
2.5 Dictionaries Operations in Python

 Same as above 2 Slides………..

109
2.5 Dictionaries Operations in Python
Traversing a Dictionary

 Traversal refers to visiting each element in the collection at least once. It is also called
iterating over loop because traversing uses loops to visit key-value pairs. Using the 'for'
loop with membership operator 'in’ makes traversing very easy.

110
2.5 Dictionaries Operations in Python
Deleting Element from a Dictionary

 To delete the key-value pair from the dictionary, you can use the functions:

 Del  del variable_name [“Key”] or del variable_name

 pop( )  variable_name.pop(“key”)

ADDITIONAL

 popitem( )  variable_name.popitem()

 clear( )  variable_name.clear()

111
2.5 Dictionaries Operations in Python
Deleting Element from a Dictionary - Del Keyword

 The keyword del is


used to delete the
key that is present
in the dictionary.

112
2.5 Dictionaries Operations in Python
Deleting Element from a Dictionary - Del Keyword

 The del keyword


can delete the
dictionary also.

 If you try to access


the dictionary
after deletion
operation, it will
raise an error.

113
2.5 Dictionaries Operations in Python
Deleting Element from a Dictionary - pop Keyword

 The pop() function


can be used to
delete a key and
its value that has
been passed as
the function
argument.

114
2.5 Dictionaries Operations in Python
Deleting Element from a Dictionary - pop Keyword

 If the key does not exist


in the dictionary, then an
error will be generated.

115
2.5 Dictionaries Operations in Python
Deleting Element from a Dictionary - popitem Keyword

 The popitem()
function removes
and returns the last
added key-value
pair in the
dictionary.

 Pairs are returned in


Last In First Out
(LIFO) order.
116
2.5 Dictionaries Operations in Python
Deleting Element from a Dictionary - clear Keyword

 The clear() function


removes all the key-value
pairs from the dictionary,
making it empty.

117
2.5 Dictionaries Operations in Python
Checking for Existence of a key

 Usual membership operators in and not in work with


dictionaries as well. But they can check for the
existence of keys only.

 The in operator will return True if the given key is


present in the dictionary, otherwise False.

 The not in operator will return True if the given key is


not present in the dictionary, otherwise False.

118
2.5 Dictionaries Functions & Methods in Python

119
2.5 Dictionaries Functions & Methods in Python

120
2.5 Characteristics of a Dictionary

121
2.5 Characteristics of a Dictionary

 Unordered: Dictionaries are unordered. A dictionary contains key-value pairs but does
not possess an order for the pairs.

 Keys are Unique and Immutable: Dictionary keys must be unique and immutable.

 Values can be Duplicate and Mutable: Values in the dictionary can be changed. Hence, it
is considered to be mutable.

 Indexed by Keys: The elements in a dictionary are indexed by keys and not numbers.

122
2.5 Difference between

123
2.6 Sorting Techniques

 Sorting in computer terms means arranging elements in a specific order — ascending or


increasing order or descending or decreasing order.

 There are multiple ways or techniques or algorithms that you can apply to sort a group of
elements such as selection sort, insertion sort, bubble sort, heap sort, quick sort etc.

 We shall cover Bubble sort and insertion sort, as recommended by syllabus.

124
2.6 Sorting Techniques – Bubble Sort

 The basic idea of bubble sort is to compare two adjoining values and exchange them if
they are not in proper order.

 See the Video

125
2.6 Sorting Techniques – Insertion Sort

 Insertion sort is a sorting algorithm that builds a sorted list one element at a time from
the unsorted list by inserting the element at its correct position in sorted list.

 See the Video

126
Python
Revision
Tour II
chapter completed.
Lesson-1

127
Thank you
[email protected]

You might also like