L8-L10 DataStructure in Python
L8-L10 DataStructure in Python
Lecture 08-10
STRINGS
Output:
Concatenated string is : Hello! world
Output:
Enter your name: Sachin
Hello! Sachin. Welcome to python.
Output:
Hello! Hello! Hello!
Syntax:
“<FORMAT>”%(<VALUES>)
Output:
Name= Abhishek and age = 9
Name = avi and age = 8
P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Output:
llo
Output:
str [1:5] = YTHO
str [:6] = PYTHON
str [1:] = YTHON
str[ : ] = PYTHON
9/12/2022
str [1:20] = YTHON Object oriented Programming Dr. Y.P.Singh 19
Slice using Negative Indexing
Use negative indexes to start the slice from the end of the
string:
Example
Get the characters from position 5 to position 1, starting the
count from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
Output:
orl
Output:
str [-1] = N
str [-6] = P
str [-2:] = ON
str[ : -2] = PYTH
str [-5:-2] = YTH
\b Backspace
9/12/2022 Object oriented Programming Dr. Y.P.Singh 24
STRING METHODS
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a
string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the
position of where it was found
format() Formats specified values in a string
Ans: *
REGULAR EXPRESSION
import re
txt = "The rain in Spain"
x = re.search("Portugal", txt)
print(x)
Output:
None
Output:
The9rain9in9Spain
Note: You can control the number of replacements by specifying the
count parameter:
9/12/2022 Object oriented Programming Dr. Y.P.Singh 38
sub() function
Example: Replace the first 2 occurrences:
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)
Output:
The9rain9in Spain
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
Output:
['ai', 'ai']
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
Output:
['The', 'rain', 'in', 'Spain’]
Note: You can control the number of occurrences by specifying the maxsplit
parameter.
import re
txt = "The rain in Spain"
x = re.split("\s", txt, 1)
print(x)
Output:
['The', 'rain in Spain']
Ans: (b)
• Sequence
• Unpacking Sequences
• Mutable Sequences
• Lists
• List Comprehension
• Looping in lists
• Tuples
• Sets
• Dictionaries
• We have used a comma “,” after the *num because the left hand side of
the assignment operation must be a tuple or list otherwise error will be
encountered.
• In the left side, when we use * operator, we can also have other variables
which can be assigned the values.
• For example, we can pack two numbers into a variable and a third
number can be assigned to another variable as follows.
num1=1
num2=2
num3=3
*num,myNum=num1,num2,num3
Object oriented Programming
9/12/2022 55
Dr. Y.P.Singh
How to perform packing
PackingininPython
Python?
Here, num3 will be assigned to myNum and num1 and num2 will be
packed in the list num.
#driver Code
my_list = [1, 2, 3, 4]
func(my_list) # This doesn't work
• Mutable Sequences:
Sequence that can change their state or contents are called mutable
sequence.
These are of type list, dict, set . Custom classes are generally
mutable.
List = [1, 2, 3, 4, 5, 6]
Output
# accessing a element
1
print(List[0])
3
print(List[2]) Output
# Negative indexing
6
print(List[-1]) # print the last element of list 4
print(List[-3]) # print the third last element of list
9/12/2022 Object oriented Programming Dr. Y.P.Singh 64
List methods
Method Description Syntax Example output
# Using insert()
List.insert(3, 12) Output
List.insert(0, 'Begin')
print(List) ['Begin', 5, 6, 12]
# Creating a List
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# using Remove() method
List.remove(5)
Output
List.remove(6)
print(List)
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
Output:
cubes of numbers from 1-10 :
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Output:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
print([(x, y) for x in [10, 20, 30] for y in [30, 10, 40] if x!=y])
Output:
[(10, 30), (10, 40), (20, 30), (20, 10), (20, 40), (30, 10), (30, 40)]
list = [1, 2, 3, 4, 5]
length = len (list)
i=0
while i < length:
print(list[i]) Output
i += 1 1
2
3
4
5
list = [1, 2, 3, 4, 5]
[print(i) for i in list]
Output
1
2
3
4
5
a) [10,34,56,[95]]
b) [10,23,56,[78]]
c) [10,23,56,[95]]
d) [10,34,56,[78]]
Answer: c
a) [10,34,56,[95]]
b) [10,23,56,[78]]
c) [10,23,56,[95]]
d) [10,34,56,[78]]
Answer: b
9/12/2022 Object oriented Programming Dr. Y.P.Singh 82
Tuples
Tuple
• A tuple is a collection which is ordered and
unchangeable. In Python tuples are written with round
brackets.
• A tuple is an immutable sequence of Python objects.
Tup = (val1, val2, …….) where val can be integer, floating number, character
or a string.
Example
tup = ("apple", "banana", "cherry")
print(tup)
Output:
('apple', 'banana', 'cherry')
9/12/2022 Object oriented Programming Dr. Y.P.Singh 85
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Example
print the second item in the tuple:
tup1 = ("apple", "banana", "cherry")
tup2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Output
print(tup1[1]) banana
print(tup2[3:6]) (4, 5, 6)
print(tup2[:4]) (1, 2, 3, 4)
print(tup2[4:]) (5, 6, 7, 8, 9, 10)
print(tup2[:]) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(tup2[-1]) // beginning from end 10
print(tup2[-3:-1]) (8, 9)
for x in thistuple:
print(x)
Output:
apple
banana
cherry
9/12/2022 Object oriented Programming Dr. Y.P.Singh 88
Tuple Assignment
It allows tuple of variables on left hand side of the assignment operator to be
assigned values from a tuple on the right hand side of the assignment operator.
Each value is assigned to its respective variable.
Example:
(a, b, c)= (1, 2, 3)
print (a, b, c)
Output
Tup1=(100, 200, 300)
(a, b, c)= Tup1 123
100 200 300
print (a, b, c)
7 6.333333 3
(a, b, c) = (3 + 4, 7 / 3 + 4, 9 % 6)
print (a, b, c)
output:
Yes, 'apple' is in the fruits tuple
9/12/2022 Object oriented Programming Dr. Y.P.Singh 90
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
index(): Searches the tuple for a specified value and returns the position
of where it was found
Tup=(1,2,3,4,5,6,7,8)
print(Tup.index(4)) Output
3
Output :
((0, 1, 2, 3), ('python', 'programming'))
SETS
Definition:
• A set is a collection which is unordered and unindexed. In Python
sets are written with curly brackets.
• A set is mutable i.e., we can easily add or remove items from a set
• Set are same as list but with a difference that sets are list with no
duplicate entries.
Example:
Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
Output:
{'banana', 'apple', 'cherry', 'orange', 'grapes', 'mango'}
Output:
3
Output
set2 = {1, 2, 3}
set1.update(set2) {'c', 3, 'a', 'b', 1, 2}
print(set1)
difference_update() Removes the items in this set that are also included in another,
specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have an intersection or not
9/12/2022 Object oriented Programming Dr. Y.P.Singh 111
SETS
Method Description
issubset() Returns whether another set contains this set or not
update() Update the set with the union of this set and others
9/12/2022 Object oriented Programming Dr. Y.P.Singh 112
Daily Quiz
Which of these about a set is not true?
a) Mutable data type
b) Allows duplicate values
c) Data type with unordered values
d) Immutable data type
Answer: d
2. Which of the following is not the correct syntax for creating a set?
a) set([[1,2],[3,4]])
b) set([1,2,2,3,4])
c) set((1,2,3,4))
d) {1,2,3,4}
Answer: a
Dictionaries
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Output:
Mustang
Mustang
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Output:
{'brand': 'Ford', 'year': 1964}
Output:
{'brand': 'Ford', 'year': 1964}
Output:
#print statement will cause an error because "thisdict" no longer exists.
Output:
{}
4. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command
do we use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)
Answer: c
9/12/2022 Object oriented Programming Dr. Y.P.Singh 135
Faculty Video Links, Youtube & NPTEL Video Links and Online Courses Details
• Strings in Python
– https://youtu.be/TXw1HseIdJw
– https://youtu.be/lSItwlnF0eU
• List in Python
– https://youtu.be/mDlSS_4BOvE
• Tuple in python
– https://youtu.be/GstQPTWpt88
• Set in Python
– https://youtu.be/MEPlLAjPvXY
• Dictionary in Python
– https://youtu.be/rZjhId0VkuY
9/12/2022 Object oriented Programming Dr. Y.P.Singh 136
Weekly Assignment 4.1
1.Give the properties of lists
2.Explain list comprehension with example.
3.Differentiate between append() and insert()
4.Write a program that prints the maximum element in second half of a list
5.Discuss the relation between tuples and lists, tuples and dictionaries in detail.
6.Python program to find and print all prime numbers in a list.
7.Python program to convert a list of tuples into a dictionary.
8.write a function that takes a list of words and returns the length of longest one.
9.Python program to combine each line from first file with the corresponding
line in second file.
10.Explain the following by giving suitable code:
i. List Comprehension
ii. Packing and unpacking in tuples
9/12/2022 Object oriented Programming Dr. Y.P.Singh 137
MCQ s
(1) Identify the right way to close a file
(a) file.close() (b) close(file)
(c) Close(“file”) (d) file.closed
Ans: (b)
• Discuss the relation between tuples and lists, tuples and dictionaries
in detail. [ Marks-6]
• Write Python Program to count the number of characters in a string
using dictionaries. Display the keys and their values in alphabetical
Order. [Marks-10]
• Write Python program to sort numbers in a list in ascending order
using Merge Sort. [ Marks-10]
• Explain the following by giving suitable code:
i. List Comprehension
ii. Packing and Unpacking in tuples
[ Marks-6]
9/12/2022 Object oriented Programming Dr. Y.P.Singh 143
Old Question Papers