0% found this document useful (0 votes)
2 views49 pages

Chapter 2 Python Revision Tour2

This document covers Python strings and lists, detailing their properties, creation methods, and various operations. It explains string indexing, immutability, string operators, membership operators, string slicing, and functions, as well as list creation, accessing, manipulation, and comparison. The document emphasizes the differences between strings and lists, particularly their mutability, and provides examples of common list operations.
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)
2 views49 pages

Chapter 2 Python Revision Tour2

This document covers Python strings and lists, detailing their properties, creation methods, and various operations. It explains string indexing, immutability, string operators, membership operators, string slicing, and functions, as well as list creation, accessing, manipulation, and comparison. The document emphasizes the differences between strings and lists, particularly their mutability, and provides examples of common list operations.
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/ 49

PYTHON REVISION

TOUR- II
Class -12
CHAPTER -2
Strings
String as a sequence of Characters

A Python String is a sequence of characters and each character can be individually accessed using its
index.
Name[0]=’P’=name[-6]
Name[0]=P=Name[-6]
Forward Indexing
Name[1]=’P’=name[-5]
Name[1]=Y=Name[-5]
0 1 2 3 4 5
Name[2]=’P’=name[-4]
Name[2]=T=Name[-4]

Name = P Y T H O N Name[3]=’P’=name[-3]
Name[3]=H=Name[-3]

Name[4]=’P’=name[-2]
Name[4]=O=Name[-2]
-6 -5 -4 -3 -2 -1
Name[5]=’P’=name[-1]
Name[5]=N=Name[-1]

Strings are immutable i.e. non-changeable (you cannot change the individual letters
of string)
String Creation
• String can be created in following ways-
1. By assigning value directly to the variable
String Literal

2. By taking Input

Input ( ) always return input in


the form of a string.

Neha Tyagi, KV 5 Jaipur II Shift


Traversal of a string
• Process to access each and every character of a string
for the purpose of display or for some other purpose is
called string traversal.
Output

Program toprint a String after reverse -

Output

Neha Tyagi, KV 5 Jaipur II Shift


String Operators
• There are 2 operators that can be used to work upon
strings + and *.
»+ (it is used to join two strings)
• Like - “tea” + “pot” will result into “teapot”
• Like- “1” + “2” will result into “12”
• Like – “123” + “abc” will result into “123abc”

»* (it is used to replicate the string)


• like - 5*”@” will result into “@@@@@”
• Like - “go!” * 3 will result “go!go!go!”

note : - “5” * “6” expression is invalid.


Neha Tyagi, KV 5 Jaipur II Shift
Membership Operators in Strings
• 2 membership operators works with strings are
• in - - returns true if character or a substring exist in
• the given string
• not in. -- returns true if character or a substring does not
exist in the given string

>>> sub = “help”


>>> string=“helping hand”
>>>sub in string
True
Membership Operators in Strings
• not in operator also results into True or False. Like-
– “k” not in “Sanjeev” will result into True.
– “ap” not in “Sanjeev” will result into True.
– “anj” not in “Sanjeev” will result into False.

>>> sub = “help”


>>>string= “helping hand”
>>>sub not in string
False
String Comparison Operators
• Look carefully at following examples -
• “a” == “a” True
• “abc”==“abc” True
• “a”!=“abc” True
• “A”= =“a”
False
• “abc” = =“Abc”
False
• ‘a’<‘A’
• ‘abcd’ > ‘abcD’
False (because Unicode value of lower case is higher than upper case)
True

How to get Ordinal/Unicode Values?


• Look at following examples-
>>>ord (‘A’) >>>char(97)
65 a
>>>ord(‘a’) >>>char(65)
97 A
String Slicing
• Look at following examples carefully-
Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13
Word R E S P O N S I B I L I T Y
Reverse index -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

word = “RESPONSIBILITY”
word[ 0 : 14 ] will result into‘RESPONSIBILITY’
word[ 0 : 3] will result into‘RES’ Note :
word[ 2 : 5 ] will result into‘SPO’
The character
word[ -7 : -3 ] will result into‘IBIL’
word[ : 14 ] will result into‘RESPONSIBILITY’
at the last
word[ : 5 ] will result into ‘RESPO’ index is not
word[ 3 : ] will result into ‘PONSIBILITY’ included in
word[1:6:2] – EPN
word[-7:-3:3] -- IL
the result
word[ : : -2] -- YIIINPE
word[ : : -1] -- YTILIBISNOPSER
String Functions
String.count(sub[,st[,end]]) Returns the number of occurrences of the given substring
String.find() sub[,st[,end]]) Returns the Lowest Index of Substring
String.index(sub[,st[,end]]) Returns Index of Substring

String.isalnum() returns True if all are Alphanumeric Character

String.isalpha() returns True if All Characters are Alphabets

String.isdigit() returns True if all Characters are digits

String.islower() returns True if all Alphabets in a String.are Lowercase

String.isupper() returns True if all characters are uppercase characters

String.isspace() returns True if there are only whitespace characters


String.lower() returns lowercased string
String.upper() returns uppercased string
String.join() Joins a string or character after each member of the string iterator.
String.swapcase() Returns a copy of string with uppercase characters converted to lowercase and
viceversa

Neha Tyagi, KV 5 Jaipur II Shift


String Functions
String.lstrip() Returns a copy of the string with leading/trailing/both whitespaces removed.
String.rstrip()
String.strip()
String.startswith(prefix[,start[,end]]) Returns True if the string starts/ends with the substring.
String.endswith(suffix[,start[,end]])
String.title() Returns the title-cased version of the string where all words starts with
uppercase characters and all remaining letters are lowecase
String.istitle() Returns True if the string has Title case
String.capitalize() Converts first character to Capital Letter

Neha Tyagi, KV 5 Jaipur II Shift


String Functions
len(<string>) Returns Length of an Object

ord(<single character) returns the ordinal Unicode value

char(<int>) Returns the character corresponding to the ordinal Unicode value.

Neha Tyagi, KV 5 Jaipur II Shift


List Creation
• List is a standard data type of Python. It is a sequence which
can store values of any kind.
•List is represented by square brackets “ [ ] “
For ex -
• [] Empty list
• [1, 2, 3] integers list
• [1, 2.5, 5.6, 9] numbers list (integer and float)
• [ ‘a’, ‘b’, ‘c’] characters list
• [‘a’, 1, ‘b’, 3.5, ‘zero’] mixed values list
• [‘one’, ’two’, ’three’] string list
• In Python, only list and dictionary are mutable data types, rest
of all the data types are immutable data types.
Creation of List
• List can be created in following ways-
• Empty list -
L=[]
• list can also be created with the following statement-
L = list( )

• Long lists-
This is tuple
even = [0, 2, 4, 6, 8, 10 ,12 ,14 ,16 ,18 ,20 ]
• Nested list -
L = [ 3, 4, [ 5, 6 ], 7]

Another method.
Keyboard input
Creation of List
-As we have seen in the example
That when we have supplied
values as numbers to a list even then
They have automatically converted to string
– If we want to pass values to a list in numeric form then we have to write
following function -
eval(input())
eval ( ) function evaluates and returns the result of an expression given as string.
L=eval(input(“Enter list to be added “))
print(L)
Output:
Enter list to be added [1,2,3]
[1,2,3]
String Values
Another example
Accessing a List
• Similarities between a List and a String.
• List is a sequence like a string.
• List also has index of each of its element.
• Like string, list also has 2 index, one for forward indexing
(from 0, 1, 2, 3, ….to n-1) and one for backward
indexing(from -n to - 1).
• In a list, values can be accessed like string.
Forward index 0 1 2 3 4 5 6 7 8 9 10 11 12 13
List R E S P O N S I B I L I T Y
Backward index -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Accessing a List
• Length of string : len( ) function is used to get the length of a list.
Important 1:membership
operator (in, not in) works
in list similarly as they work
in other sequence.

• Indexing : L[ i ] will return the values exists at i index.


• Slicing : L [ i : j ] will return a new list with the values from i index to j index
excluding j index.

Important 2: + operator
adds a list at the end of
other list whereas *
operator repeats a list.
Difference between a List and a String
• Main difference between a List and a string is that
string is immutable whereas list is mutable.
• Individual values in string can’t be change whereas it is
possible with list.

Value didn’t
change in string.
Error shown. Value got changed
in list specifying
list is mutable
Traversal of a list
• Traversal of a list means to access and process each
and every element of that list.
• Traversal of a list is very simple with for loop –
for <item> in <list>:
Process each item here

*Python supports UNICODE therefore


output in Hindi is also possible
Comparison of Lists
• Relational operators are used to compare two different lists.
• Python compares lists or tuples in lexicographical order,
means comparing sequences should be of same type and
their elements should also be of similar type.

Some
examples

• In first example, python did not


raise the error because both the
lists are same.
• In second comparison, both the
lists are not similar hence, pytho n
raised the error.
List Operations (+, *)
• + (Concatenation operator)
• To join Lists,+ operator , is used which joins a list at the end of other list.
With + operator, both the operands should be of list type otherwise
error will be generated.

• Note:
• Following expression will result into error • Operator a+=b does not
expand to a=a+b if a is a list.
• List+number
For list += requires an iterable
• list+complex-number on the right and it adds each
• List+string element of the iterable to the
list.
• Exception :
>>>L1=[1,2,3] >>>L1=[1,2,3]
>>>L1+=“abc” >>>L1=L1+”abc”
>>>print(L1) >>>print(L1)
Output : [1,2,3,’a’,’b’,’c’] Output : ERROR
List Operations (+, *)
• * (Replication operator)
• To replicate a list, * operator , is used.
List Slicing
• To slice a List, syntax is seq = list [ start : stop ]

• Another syntax for List slicing is –


seq=list[start:stop:step]
Use of slicing for list Modification
• Look carefully at following examples-

New value is being assigned here.

Here also, new value is being assigned.

See the difference between both the results.

144 is a value and not a sequence.


Making true copy of a list

Lstcopy=list[ : ]
List Manipulation
• Element Appending in List list.append(item)

• Updating List elements list[index]=<new value>

• Deletion of List elements del list[index]


Important: del
command can be
used to delete an Important: if we write
element of the list >> del <list>
or a complete slice
complete list will be deleted.
or a complete list.
List Manipulation
• Only one element will be deleted on pop() from list.
• pop ( ) function can not delete a slice.
• pop ( ) function also returns the value being deleted.
list.pop(<index>)

Last item

6th item

1st item
Function Details Returns
len(<list>) Returns the number of elements length
in the passed list

list(<sequence>) Returns a list from the passed list


argument. If no argument is
passed returns empty list
list.index(<item>) Returns the index of first matched index
item.
list.append(<item>) Adds the passed item at the end No value
of list.
(Takes one element)
list.extend(<list>) Append the list (passed in the No value
form of argument) at the end of
list.
(Adds multiple elements)
list.insert(<pos>,<item>) Insert the passed element at any No value
position of your choice.
Function Details Returns
list.pop(<index>) Delete and return the element the item being
of passed index. Index passing deleted
is optional, if not passed,
element from last will be
deleted.
list.remove(<value>) It will delete the first No value
occurrence of passed value but
does not return the deleted
value.
list.clear ( ) It will delete all values of list . No value
the list object still exist as
empty list
del <listname> Delete all the elements and the No value
list object too

del list[<index>] To remove element at given No value


index
del list[<start>:<stop>] To remove element in list slice No value
list.count (<item>) It will count and return number of return number
occurrences of the passed element. of occurrences
of the passed
element.
list.reverse ( ) It will reverse the list and it does not No value
create a new list.
list.sort ( ) It will sort the list in ascending order. To No value
sort the list in descending order, we
need to write----- list.sort(reverse
=True).
sorted(<iterable Returns a new sorted list but does not New sorted list
sequence>, modify the list passed as argument.
[reverse=False])
min(<list>) Returns the Minimum value of the list Minimum value
(must contain all elements of same
type)
max(<list>) Returns the Maximum Value of the list Maximum value
sum(<list>) Returns the sum of the elements of list sum
(must contain elements such as
numbers)
Tuple Introduction
• A tuple is a standard data type of python that can store a
sequence of values belonging to any type.

• Tuple is an immutable data type which means we can not


change any value of tuple.

• Tuple is a sequence like string and list but the differenceis


that list is mutable whereas string and tuple are immutable.
Creation of Tuple
• In Python, “( )” parenthesis are used for tuple creation.
() empty tuple
( 1, 2, 3) integers tuple
( 1, 2.5, 3.7, 7) numbers tuple
(‘a’, ’b’, ’c’ ) characters tuple
( ‘a’, 1, ‘b’, 3.5, ‘zero’) mixed values tuple
(‘one’, ’two’, ’three’, ’four’) string tuple

*Tuple is an immutable sequence whose values can not be changed.


Creation of Tuple
Look at following examples of tuple creation carefully-
• Empty tuple: OR T= tuple()

• Single element tuple:


Here 1 is treated a integer

So to construct a tuple with one element add a comma after single element

>>> t=3, OR >>> t=(3,)


>>>print(t) >>>print(t)
(3,) (3,)
Creation of Tuple

Look at following examples of tuple creation carefully-

• Long tuple:

• Nested tuple:
Creation of Tuple
tuple() function is used to create a tuple from other sequences.
Syntax : tuple(<sequence>)
See examples-
Tuple creation from string Tuple creation from list

Tuple creation from input

All these elements are of


character type. To have
these in different types,
need to write following
statement.-
Tuple=eval(input(“Enter
elements”))
Accessing a Tuple
• In Python, the process of tuple accessing is same as
with list. Like a list, we can access each and every
element of a tuple.

• Similarity with List- like list, tuple also has index. All
functionality of a list and a tuple is same except mutability.
Forward index 0 1 2 3 4 5 6 7 8 9 10 11 12 13
Tuple R E S P O N S I B I L I T Y
Backward index -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

• len ( ) function is used to get the length of tuple.


Accessing a Tuple
• Indexing and Slicing:
• T[ i ] returns the item present at index i.

• T[ i : j ] returns a new tuple having all the items of T from index i to


j excluding index j.

returns a new tuple having difference of n elements of T from


• T[i:j:n]
index i to j excluding index j
Accessing a Tuple

• Membership operator:
• Working of membership operator “in” and “not in” is same as
in a list.
• in – checks if an element is present in the tuple or not
• not in – checks if an element is not present in the tuple

• Concatenation and Replication operators:


+ operator adds second tuple at the end of first tuple.

* operator repeats elements of tuple.


Accessing individual elements of a Tuple
• Accessing Individual elements-

• Traversal of a Tuple –
for <item> in <tuple>:
#to process every element.

OUTPUT
Immutable types with mutable elements
An immutable tuple can store mutable elements and its mutable elements can be
changed

>>>Numbers=( [1,2,3], [4,5,6])

>>>Numbers[1]=[1,2,0] (replacing the value at index no. 1)


ERROR (tuples are immutable)

>>>Numbers[1][2]=0 ((No error- as tuple element is a list and


lists are mutable)
>>>print(Numbers)
( [1,2,3], [4,5,0])
Tuple Operations
• Tuple joining
• (using + the concatenation operator)

• The + operator requires that both the operands must be


of tuple types

Some errors in tuple joining-


• In Tuple + number
• In Tuple + complex number
• In Tuple + string
• In Tuple + list
• Tuple + (5) will also generate error because when adding a tuple with a single
value, tuple will also be considered as a value and not a tuple..
Tuple Operations

• Repeating or Replicating tuples


• (using * operator)

• The * operator requires a tuple and an integer as operands.


Tuple Slicing

Tuple will show till last element of list irrespective of upper


limit.

Every alternate element will be shown.

Every third element will be shown.

>>>tp1[4: 1 : 1]
()
Tuple Slicing
• The + and * operator with tuple slices

>>>tp1=(1,2,3,4,5,6)
>>>tp1[2:5]*3
(3,4,5,3,4,5,3,4,5)

>>>tp1[2:5] + (3,4)
(3,4,5,3,4)
Tuple Comparision

Note:
For two tuples to be equal they
must have same number of
elements and matching values.
Tuple unpacking

Note:
Tuple unpacking requires that
the list of variables on the left
has the same number of
elements as the length of the
tuple.
Tuple Deletion
As we know that tuple is of immutable type, it is not possible to delete an individual
element of a tuple. With del() function, it is possible to delete a complete tuple.
Look at following example-

Error shown because


deletion of a single
element is also possible.

Complete tuple has


been deleted. Now
error shown on printing
of tuple.
Function Details Returns
len(<tuple>) Returns the number of length
elements in the passed
tuple
tuple(<sequence>) Returns a tuple from tuple
the passed argument.
If no argument is
passed returns empty
tuple
tuple.index(<item>) Returns the index of Index
first matched item.
Function Details Returns
tuple.count (<item>) It will count and return number of return number
occurrences of the passed element. of occurrences
of the passed
element.
sorted(<iterable Returns a new sorted tuple but does New sorted
sequence>, not modify the list passed as argument. tuple
[reverse=False])
min(<tuple>) Returns the Minimum value of the tuple Minimum value
(must contain all elements of same
type)
max(<tuple>) Returns the Maximum Value of the Maximum value
tuple
sum(<tuple>) Returns the sum of the elements of Sum
tuple
(must contain elements such as
numbers)
del <tuple_name> Deletes the complete tuple No value

You might also like