Python Ch-5_Notes
Python Ch-5_Notes
Example 1
str = "HELLO"
str[0] = "h"
print(str)
O/P:
Traceback (most recent call last):
File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment
However, in example 1, the string str can be assigned completely to a new content as
specified in the following example.
Example 2
str = "HELLO"
print(str)
str = "hello"
print(str)
O/P:
HELLO
hello
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the
string. But we can delete the entire string using the del keyword.
str = "PYTHON"
del str[1]
O/P:
TypeError: 'str' object doesn't support item deletion
str1 = "PYTHON"
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 2
Python Programming (UNIT-5) | 4311601
del str1
print(str1)
O/P:
NameError: name 'str1' is not defined
List out various String operations and Explain any one with example WINTER 2021,2022,
SUMMER 2022
String Operations
Various operations that can be performed on strings are:
Accessing String Characters
Traversing a String
Slicing a String
Searching a String
String Concatation
String Repetition
str[0]=H
str[1]=E
str[4]=O
str[-1]=O
str[-2]=L
str[-4]=E
Write a program to traverse the string using for and while loop. WINTER-2022
Traversing a String
Different ways to iterate strings in Python. You could use a while loop,for loop, range in
Python, a slicing operator, and a few more methods to traverse the characters in a string.
Another quite simple way to traverse the string is by using the Python range function. This
method lets us access string elements using the index.
Example:
string_to_iterate = "Data Science"
for char_index in range(len(string_to_iterate)):
print(string_to_iterate[char_index])
O/P: Data Science
Slicing a String
# Slicing Operator
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 4
Python Programming (UNIT-5) | 4311601
string [starting index : ending index : step value]
To use this method, provide the starting and ending indices along with a step value and
then traverse the string. Below is the example code that iterates over the first six letters
of a string.
Here, Start_Index is the starting index of the string. End_Index is the last index before
which all elements are considered.
Steps are the number of steps to be jumped in each iteration. The Start_Index and Steps
are optional. The Start_Index is 0 by default. The step is 1 by default.
Note that ending index is not included in the range.It means Mystring[3:7] starting
from Mystring[3] to Mystring[6].index 7 is not included.
Example:
string_to_iterate = "Python Data Science"
for char in string_to_iterate[0 : 6 : 1]:
print(char)
O/P: Python
You can take the slice operator usage further by using it to iterate over a string but
leaving every alternate character. Check out the below example:
Example:
string_to_iterate = "Python_Data_Science"
for char in string_to_iterate[ : : 2]:
print(char)
O/P: P t o _ a a S i n e
Example:
string_to_iterate = "Machine Learning"
for char in string_to_iterate[ : : -1]:
print(char)
O/P: g n i n r a e L e n i h c a M
Example:
string_to_iterate = "Machine Learning"
char_index = len(string_to_iterate) - 1
while char_index >= 0:
print(string_to_iterate[char_index])
char_index -= 1
O/P: g n i n r a e L e n i h c a
Searching a String
If you want to check whether a particular substring exists in the string or not use the
Python string in operator.
If the substring is present in the string, True is returned, otherwise False is returned. It
is case-sensitive.
Example:
Mystring = “Welcome To Python”
print(“Python” in Mystring)
print(“python” in Mystring)
O/P
True
False
String Concatation
Example:
x = "Python is "
y = "awesome"
z= x+y
print(z)
O/P
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 6
Python Programming (UNIT-5) | 4311601
Python is awesome
String Repetition
The repetition operator is denoted by a '*' symbol and is useful for repeating strings to
a certain length.
Example:
str = 'Python program'
print(str*3)
O/P
Python programPython programPython program
Introduction to List
In Python, the sequence of various data types is stored in a list. A list is a collection of
different kinds of values or items. The comma (,) and the square brackets [enclose the
List's items] serve as separators.
Lists are used to store multiple items in a single variable.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 10
Python Programming (UNIT-5) | 4311601
Elements of the List need not be of same type.It means List can represents
homogeneous(same) as well as heterogenous(different) elements.
Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Mutable: In list element(s) are changeable. It means that we can modify the items stored
within the list.
Dynamic: List can expand or shrink automatically to accommodate the items accordingly.
Duplicate Elements: Lists allow us to store duplicate data.Lists are created using square
brackets:
Types of Lists:
Homogenous List:
Heterogenous List:
List out various List operations and Explain any one with example. WINTER – 2021,
WINTER-2022
Explain how to create list by giving example. WINTER - 2021
Explain indexing and slicing operations in python list.WINTER-2022
List Operations
Various operations that can be performed on list are:
Creating a list
Access individual Element of the List.
Traversing in a List
Searching a List
List Concatation
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 11
Python Programming (UNIT-5) | 4311601
List Repetition
Creating a list
To create a list in Python, we use square brackets ([]). Here's what a list looks like:
ListName = [ListItem, ListItem1, ListItem2, ListItem3, ...]
# Creating an empty List
empty_List = []
Print(List_1)
Elements stored in the lists are associated with a unique integer number known as an
index. The first element is indexed as 0, and the second is 1, and so on. So, a list
containing six elements will have an index from 0 to 5.
For accessing the elements in the List, the index is mentioned within the index
operator ([ ]) preceded by the list's name.
Example:
print(My_List[2])
print(My_List[4])
print(My_List[-1])
print(My_List[-5])
O/P: 6 8 8 3
we can access the elements stored in a range of indexes using the slicing operator (:).
The index put on the left side of the slicing operator is inclusive, and that mentioned
on the right side is excluded.
Slice itself means part of something. So when we want to access elements stored at
some part or range in a list we use slicing
Example:
my_List = ['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']
print(my_List[:6])
print(my_List[5:])
print(my_List[:])
print(my_List[:-6])
print(my_List[-8:-5])
sO/P:
['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']
Traversing in a List
Traversing a list means access each elements of list.
Example:
list1 = [3, 5, 7, 2, 4]
count = 0
while (count < len(list1)):
print (list1 [count])
Example:
list1 = [3, 5, 7, 2, 4]
for i in list1:
print (i)
O/P: 3 5 7 2 4
Example:
list1 = [3, 5, 7, 2, 4]
length = len (list1)
for i in range (0, len (list1)):
print (list1 [i])
O/P: 3 5 7 2 4
Searching a List
You can search elements in a list usinh Membership operator
Membership Check of an element in a list: We can check whether a specific element is
a part/ member of a list or not.
Example:
my_List = [1, 2, 3, 4, 5, 6]
print(3 in my_List)
print(10 in my_List)
print(10 not in my_List)
List Concatation
One list may be concatenated with itself or another list using ‘+’ operator.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 15
Python Programming (UNIT-5) | 4311601
Example:
List1 = [1, 2, 3, 4]
List2 = [5, 6, 7, 8]
concat_List = List1 + List2
print(concat_List)
O/P: [1, 2, 3, 4, 5, 6, 7, 8]
List Repetition
We can use the ‘*’ operator to repeat the list elements as many times as we want.
Example:
my_List = [1, 2, 3, 4]
print(my_List*2)
O/P: [1, 2, 3, 4, 1, 2, 3, 4]
List built in methods of list and give their use. WINTER – 2021
Differentiate remove( ) and pop( ) methods of list with suitable example. SUMMER-
2022
List Methods and Built-in Functions
print(fruits)
print(fruits)
O/P: ['apple', 'cherry'] ['apple',
'banana']
count() Returns the number of elements with the Example:
specified value fruits = ["apple", "banana",
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 17
Python Programming (UNIT-5) | 4311601
"cherry"]
x = fruits.count("xyz")
print(x)
fruits = ["apple", "banana",
"cherry","banana"]
x = fruits.count("banana")
print(x)
O/P: 0 2
sort() Sort the list alphabetically Example:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
O/P: ['BMW', 'Ford', 'Volvo']
reverse() Reverses the order of the list Example:
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
O/P:['cherry', 'banana', 'apple']
index() Returns the index of the first element with Example:
the specified value fruits = ['apple', 'banana',
'cherry','cherry']
x = fruits.index("cherry")
print(x)
O/P:2
min() Returns the smallest of the values or the Example:
smallest item in an list list1 = [10, 20, 4, 45, 99]
print(min(list1))
O/P: 4
max() Returns the largest of the values or the Example:
largest item in an list list1 = [10, 20, 4, 45, 99]
print(max(list1))
A list can contain another list (sublist), which in turn can contain sublists themselves,
and so on. This is known as nested list.
You can use them to arrange data into hierarchical structures.
Example:
An existing list can be copied into new list using slicing method
Example:
List1=[“A”,”B”,”C”]
List2 = List[ : ]
Print(List2)
O/P: [‘A’,’B’,’C’]
(2) Using list() constructor
An existing list can be copied into new list using list() method
Example:
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani] 20
Python Programming (UNIT-5) | 4311601
List1=[“A”,”B”,”C”]
List2 = list(sList1)
Print(List2)
O/P: [‘A’,’B’,’C’]
(3) Using copy() method
An existing list can be copied into new list using copy() method available in standard
library named copy
Example:
Import copy
List1=[“A”,”B”,”C”]
List2 = copy.copy(List1)
Print(List2)
O/P: [‘A’,’B’,’C’]
We can use assignment operator(=) in order to create an alias of existing list.
Alias refers to the altername name of list.
Example:
List1=[“A”,”B”,”C”]
List2 = List1
In above example we assign List1 to List2 using assignment operator.
It will not create a copy od List1 but it create an alias of List1.
It means, both List1 and List2 refers to the same element in memory.
If you can change value of any element in List it will affect to both List.
Example:
List1=[“A”,”B”,”C”]
List2 = List1
List1[0]=”E”
print(List1)
print(List2)
O/P: [‘E’,’B’,’C’] , [‘E’,’B’,’C’]
Example:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
**********