Module 1 DataStructure&Comprehension
Module 1 DataStructure&Comprehension
Syllabus:
• Basics of Python Programming
• Data Structures: Set, Dictionary, Tuple, List, and String.
• Operations ,Comprehensions, and Methods for each
data structure.
Basics of Python Programming
String in python
Strings are a sequence of character.
Creating strings
Accessing strings
Adding chars to strings
Editing Strings
Deleting Strings
Operations on string
String function
Basics of Python Programming
String in python
Creating strings a = '''Hello world’‘’ //for multiline string
a = ‘Hello world’ print(a)
print(a)
‘Hello world’ Double inverted comma is also allowed.
a = 'Thanks god, it's monday’
print(a) => error c = str("hello")
To resolve this error, use double inverted comma. c
a = "Thanks god, it's monday“
print(a)
Basics of Python Programming
Accessing substring from a string Types of indexing:
1. Positive indexing.
#Concept of indexing:
2. Negative indexing.
c = "hello“
print(c[-1]) =>o
print(c)
print(c[-2])=>l
print(c[0])
print(c[1])
Types of indexing:
1. Positive indexing.
2. Negative indexing.
Basics of Python Programming
Accessing substring from a string
c = "world“
Empty string =>False for i in c[0:-1]:
Non empty string =>True print(i)
Output:
w
“Hello” and “World” => world o
"" or "world“ => ‘world’ r
l
c = "world“
for i in c:
print(i)
w
o
r
l
d
Basics of Python Programming
Membership operations:
in , not in
‘h’ in c
True
Basics of Python Programming
String function in python
a = “delhi”
len(a) => 5
Common function: max(a) => l
• len min(a) => d
• max sorted(a) => ['d', 'e', 'h', 'i', ‘l’]
• min sorted(a,reverse=True)=>
• sorted
['l', 'i', 'h', 'e', 'd']
Basics of Python Programming
String function in python
a = “delhi”
[Link]()=> DeLhI
Basics of Python Programming
String function in python
Count() gives frequency of character or substring in the
string.
a = "Today is wednesday“
Functions applicable only on string data [Link]('e’) =>2
type. [Link](‘ay’) => 2
• Count
• find/Index Find() gives position of character or substring in the given
string
“Today is wednesday”.find(“T”) =>0
“Today is wednesday”.find(“wed”) =>10
“Today is wednesday”.find(“p”) =>-1
"hello_world".isidentifier()=>True
"hello-world".isidentifier()=>False
Basics of Python Programming
String function in python
"what else remaining in our course".split()
Output:['what', 'else', 'remaining', 'in', 'our', 'course']
• Split
"what else remaining in our course".split('i’)
Split converts string into list. Output:['what else rema', 'n', 'ng ', 'n our course’]
• Join
" ".join(['what', 'else', 'remaining', 'in', 'our', 'course’])
Join is the reverse of split function. 'what else remaining in our course'
List vs Array:
Array is homogenous, but List is heterogenous.
Array is contiguous memory allocation.
Arrays are much faster than list.
Create a List:
L = [] #empty list
L
[]
L=[1,2,3,4,5]
L
[1,2,3,4,5]
Data Structure
L=[“Hello”,2,”world”,’c’,5]
L
[“Hello”,2,”world”,’c’,5]
Multi-dimensional List:
2D List:-
L2 = [1,2,3,[5,6]]
L2
[1,2,3,[5,6]]
Data Structure
Multi-dimensional List:
3D List:-
L3 = [[[1,2],[3,4]],[[5,6],[7,8]]]
L3
[[[1,2],[3,4]],[[5,6],[7,8]]]
L4 = list(“Noida”)
L4
[‘N’,’o’,’i’,’d’,’a’]
L5 = list()
[]
Data Structure
How to access list. L3=[1,2,3,4,[5,6]] x = L3[4]
L[-1]
L3 x[0]
Output: 5
L = [1,2,3,4,5] Output:[1, 2, 3, 4, [5, 6]] Output: 5
L
L[1:3] L3[4] x[1]
Output: [1, 2, 3, 4, 5]
Output: [2,3] Output: [5, 6] Output: 6
• Extend
• If multiple element need to insert [Link]("hello")
in the list. L
Output: [1, 2, 3, 4, 5, 'h', 'e', 'l', 'l', 'o']
• insert
Data Structure
L = [1,2,3,4,5]
[Link](1,"hello")
How to add. L
Output: [1, 'hello', 2, 3, 4, 5]
• Insert
• This function insert the element
in the specified position.
Data Structure
del L
How to delete.
del L[1]
• del
del L[-2] {delete second element from last}
4. 4 in L1
Output: False
Data Structure
Operations on the list L = [1,2,3,4]
len(L)
• len
• Compute the length of list. 4
• min
• It find out minimum number. min(L)
• Max Output: 1
• It find out maximum number.
• Sorted max(L)
• It sort the element in the [Link] is not permanent
operation. Output: 4
• Reverse sort
• It sort the list in reverse order. This is not a sorted(L)
permanent operation. A new list is formed.
Output: [1,2,3,4]
sorted(L,reverse = True)
Output: 4,3,2,1
Data Structure
L= [3,2,1]
Operations on the list
[Link]()
• Sort
• It sort the list permanently L = [1,2,3]
• Reverse the list
• It reverse the list permanently [Link](reverse = True)
• Index L
• It gives index of an element. Output: [3,2,1]
[Link](2)
Output: 1
Data Structure
Operations on the list
Write a program to convert string like
this form:
string = xyz@[Link]
list=[Link]("@")
print(list[0])
Data Structure
Operations on the list
Write a program to remove element
from given list:
L1=[1,1,2,2,2,3,3,4,4]
Input: [1,1,2,3,3,3,4,4] L=[]
Output: [1,2,3,4]
for i in L1:
if i not in L:
[Link](i)
print(L)
Data Structure
Tuple: It is similar as List.
• Create Tuples
• Access Tuples
• Edit
• Add
• Delete
• Operations
• Functions
Data Structure
• Create Tuples T3 = (1,2,(3,4),(4,5))
How to create empty tuples. T3
(1, 2, (3, 4), (4, 5))
T1 = ()
T6=tuple("git")
T6
type(T6) =>tuple
T1[-1] T4=(1,2,3,(4,5),(7,8))
4 T4
T4[-1][0] => 7
Data Structure
• Edit tuple.
del T1
T2=(1,2,3,4,5)
del T2[-1] => ?
You can not delete part of a tuple.
Because tuples are immutable.
Data Structure
• Operations on tuple.
T1= (1, 2, 3, 4)
T2 = ('Hello', 2, 3, 4)
• Concatenate
T2 = ('Hello', 2, 3, 4) For I in T2:
• Multiply T1+T2 print(i)
• Loop (1, 2, 3, 4, 'Hello', 2, 3, 4) Hello
• Membership operator 2
3
All operations are adjactly same as list. All functions are also 4
same as list. T1*2
(1, 2, 3, 4, 1, 2, 3, 4)
I in T2
Tuples are read-only data type. It is used where data-integrity
is important. False
Data Structure
• Sets
S1 = {}
• Sets do not allow duplicates. {}
• Sets have no indexing/slicing. type(s1) => dict(default behavious is
• Sets don’t allow mutable data [Link] dictionary)
means list is not a member of sets, but
tuple can be a member of sets.
• Set itself is a mutable data type. So 2-d
set or 3-d set is not possible. So, to create empty set, you have to
• Set is an unordered data structure, so create like below.
the output order can change. S1 = set()
S1
Set()
type(S1) => set
Data Structure
Homogeneous set:
• Sets S1 = {1,2,3,4,5}
S1
• We can create homogeneous set as {1,2,3,4,5}
well as heterogeneous set.
• Set is implemented using a hash Heterogeneous set:
table, not a list. So the order you
S1 = {“world”,3,4,5}
see is not insertion order.
S1
{'world', 3, 4, 5}
s2={"Hello",2,3}
s2
{2, 3, 'Hello'}
Data Structure
• Sets • The hash value is the integer itself.
hash(2) = 2
hash(3) = 3
• When you write ,
S1= {“Hello”,2,3} Python uses special hashing algorithm called , siphash.
Python doesn’t store it like {“Hello”,2,3}
Instead, for every element, python computes a value called a hash. hash(“Hello”) is computed using siphash.
•
•
Data Structure
Question: why duplicate is not allowed in set.
Answer: Because of hashing internal mechanism, duplicates are not allowed.
When you insert an element into s set, python compute the hash:
h = hash(element)
Control go to the slot decided by that hash.
If element is already there, python checks,
existing_element == new_element
s1 = {1,2,3,4} Convert the set in the list, and edit the list. And again convert it into set.
s1 s1 = {1,2,3,4}
{1, 2, 3, 4}
s1
s1[0]
{1, 2, 3, 4}
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
id(s1)
s1[0] 2070386626112
TypeError: 'set' object is not subscriptable L = list(s1)
L[0]=50
s1[:2]
L
Traceback (most recent call last):
[50, 2, 3, 4]
File "<pyshell#30>", line 1, in <module>
s1[:2]
s1 = set(L)
TypeError: 'set' object is not subscriptable s1
{3, 50, 2, 4}
id(s1)
2070386626784
Address is different. So we can’t edit set.
Data Structure
• How to add item in the Sets:
S1 =
{3, 50, 2, 4}
[Link](6)
s1
{2, 3, 4, 6, 50}
id(s1)
2070386626784
[Link](10)
s1
{2, 3, 4, 6, 10, 50}
id(s1)
2070386626784
s3
{1, 2, 3}
[Link](3)
s3
{1, 2}
Data Structure
2. Multiplication:
• Set Operators:
s1
1. Concatenation {2, 3, 4, 5}
S1 s1*3
{2, 3, 4, 5} Traceback (most recent call last):
s2 = {"Hello",True,3,4}
File "<pyshell#88>", line 1, in <module>
s2
s1*3
{True, 'Hello', 3, 4}
s1+s2 TypeError: unsupported operand type(s)
for *: 'set' and 'int’
Traceback (most recent call last):
File "<pyshell#85>", line 1, in <module>
s1+s2 Cancatenation and multiplication is not
TypeError: unsupported operand type(s) for +: 'set' supported in sets.
and 'set'
Data Structure
2. Membership operator
• Set Operations:
s2
1. Loop {True, 'Hello', 3, 4}
3 in s2
s2 True
{True, 'Hello', 3, 4}
for i in s2:
print(i)
Output:
True
Hello
3
4
Data Structure
s1
• Set functions {2, 3, 4, 5}
s2
{True, 'Hello', 3, 4}
1. Len(s1)
[Link](s2)
2. Min(s1)
{True, 2, 3, 4, 5, 'Hello’}
3. Max(s2)
4. sorted(s1) [Link](s2)
5. Sorted(s1,reverse=True) {3, 4}
6. Union
7. Intersection [Link](s2)
8. Defference {2, 5}
[Link](s1)
{True, 'Hello’}
Data Structure
s1
• Set functions {2, 3, 4, 5}
s2
{True, 'Hello', 3, 4}
1. Symmetric_difference
s1.symmetric_difference(s2)
2. Disjoint
{True, 2, 5, 'Hello’}
3. Subset
4. superset [Link](s2)
False
[Link](s2)
False
[Link](s2)
False
Data Structure
• Dictionary Mutable datatypes:
Lists/Sets/Dictionary
1. Dictionary consist of key value pair.
Immutable datatypes.
d = {"name": "Ajay", "age": 25} String/tuples/int/float/Boolean/Complex
“name” =>Key
“Ajay” => Value
2. Dictionary has no indexing.
3. Dictionary is a mutable types.
4. Values can be mutable but keys are immutable.
5. Keys should be unique.
Data Structure
• How to create Dictionary. D4 =
{"Name":"Vijay","College":"GNIOT","Marks":{"DS
D = {} ":35,"Hindi":38,"Math":45}}
D D4
type(D) = <class ‘dict’> {'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS':
35, 'Hindi': 38, 'Math': 45}}
D = {"Name":"Ajay","Gender":"Male"}
D
{'Name': 'Ajay', 'Gender': 'Male’}
D3 = {"Name":"sham","Name":"Ajay"}
D3
{'Name': 'Ajay'}
Data Structure
• How to access item from a Dictionary. D4
{'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS':
D 35, 'Hindi': 38, 'Math': 45}}
{'Name': 'Ajay', 'Gender': 'Male'}
D[0] D4["Marks"]
Traceback (most recent call last): {'DS': 35, 'Hindi': 38, 'Math': 45}
File "<pyshell#178>", line 1, in <module> D4["Marks"]["Math"]
D[0]
45
KeyError: 0
D["Name"]
'Ajay'
D["Gender"]
'Male'
Data Structure
• How to edit item from a Dictionary. D4
{'Name': 'Vijay', 'College': 'GNIOT', 'Marks':
D {'DS': 35, 'Hindi': 38, 'Math': 45}}
D D4
D
D4["Marks"]["Eng"]=40
{'Name': 'Biploy', 'Gender': 'Male'}
D["Age"]=20 D4
{'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS':
35, 'Hindi': 38, 'Math': 48, 'Eng': 40}}
D
{'Name': 'Biploy', 'Gender': 'Male', 'Age': 20}
Data Structure
Delete individual key-value pairs,
• How to delete. D
{'Name': 'Biploy', 'Gender': 'Male', 'Age': 20}
D
{'Name': 'Biploy', 'Gender': 'Male’} del D["Gender"]
del D
D
{'Name': 'Biploy', 'Age': 20}
[Link]()
D
{}
It gives empty dictionary.
Data Structure
D4
{'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS': 35, 'Hindi': 38, 'Math': 48,
'Eng': 40}}
• What operation can be performed.
for i in D4:
print(i)
Concatenation and Multiplication will not work.
Output:
Name
College
Loop will work.
Marks
D4
Membership operation will also work.
{'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS': 35, 'Hindi': 38, 'Math': 48,
'Eng': 40}}
for i in D4:
print(i,D4[i])
Output:
Name Vijay
College GNIOT
Marks {'DS': 35, 'Hindi': 38, 'Math': 48, 'Eng': 40}
Data Structure
Membership operation will also work.
D4
{'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS': 35, 'Hindi': 38, 'Math': 48,
'Eng': 40}}
"Vijay" in D4
False
"Vijay" in [Link]()
True
"Math" in D4["Marks"]
True
"Name" in D4
True
Len(D)
[Link]()
Min(D)
dict_keys(['Name', 'College', 'Marks’])
Max(D)
Sorted(D)
Sorted(D3, reverse=“True”)
[Link]()
dict_values(['Vijay', 'GNIOT', {'DS': 35, 'Hindi': 38,
'Math': 48, 'Eng': 40}])
Data Structure
Comprehension
In python, comprehension is a concise and elegant way to create new sequence (lists, dictionaries, and sets)
from existing ones using a single line of code . It replaces traditional for loops and makes the code more
readable ,efficient, and pythonic.
The basic syntax combines an expression , a loop, and an optional conditional clause within appropriate
delimiters(square brackets, curly, braces, or parentheses ).
List comprehension is a short and clean way to create a new list from another iterable (like list,
range, string, etc.) using a single line of code.
General Syntax: [ expression for item in iterable ]
Data Structure
***Normal way***
L = []
for i in range(1, 6): sqr = []
[Link](i*i) sqr = [i*i for i in range(1,6)]
sqr
[1, 4, 9, 16, 25]
***List comprehension***
L = [i*i for i in range(1, 6)] sqr = [i for i in sqr if i<9]
sqr
[1, 4]
Data Structure
Set comprehension is a short and clean way to create a set from an iterable (like list, range, string, etc.).
s = {x for x in range(5)}
print(s)
{0, 1, 2, 3, 4}
{0, 2, 4, 6, 8}
lst = [3,3,5,5,6,6,7,7]
List comprehension:
[x for x in range(5)]
Set comprehension:
{x for x in range(5)}
Tuple comprehension:
T = (x for x in range(5))
T
<generator object <genexpr> at 0x000001E2110C28F0>
It means (x for x in range(5)) is a generator expression. It is not a tuple.
You must convert the generator to a tuple.
t = tuple(x for x in range(5))
print(t)
(0, 1, 2, 3, 4)