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

Module 1 DataStructure&Comprehension

The document provides an extensive overview of Python fundamentals, focusing on string manipulation and data structures such as lists. It covers string creation, editing, operations, and various string functions, as well as the characteristics and operations of lists, including creation, access, modification, and deletion. The content is structured as a syllabus followed by detailed explanations and examples for each topic.

Uploaded by

chumeoa8
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 views68 pages

Module 1 DataStructure&Comprehension

The document provides an extensive overview of Python fundamentals, focusing on string manipulation and data structures such as lists. It covers string creation, editing, operations, and various string functions, as well as the characteristics and operations of lists, including creation, access, modification, and deletion. The content is structured as a syllabus followed by detailed explanations and examples for each topic.

Uploaded by

chumeoa8
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

Module-1:Python fundamentals

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.

In python specifically, strings are a sequence of Unicode characters.

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

#Concept of slicing: print(a[:])


Hello world
a = "Hello world“
print(a)
print(a[0:4]) print(a[2:8:2]) #Skip one character
Low
Output:
Hello world print(a[0:6:-1]) =>No Output
Hell print(a[-5:-1:2])
print(a[4:])
Output: wr
Output: o world
print(a[::-1]) =>String will reverse
print(a[:4])
Output: Hell print(a[-1:-5:-1])
Output:dlro
Basics of Python Programming
Editing and deleting in string a = "Hello world“
print(a)
a = "Hello world“
Output: Hello world
a[0] = ‘x’
Output: error message.
#Strings are immutable data type. del(a)
print(a)
We can completely reassign string . Output: Name a is not defined.
a = “generic”
print(a)
We can not delete particular
Output: generic character.
del(a[0]) =>error
We can not edit string.
Basics of Python Programming
Arithmetic operations:
Operations on string: String concatenation:
“Hello”+”world”
Arithmetic operations
Relational operations
Logical operations print(“Hello”*2)
Loops on string HelloHello
Membership operations Relational Operations:
“Hello” == “world” =>False
“Hello” != “world” =>True

“abcde” > “xy” #Lexicographically


Output: False
Basics of Python Programming
Logical operations: Loop operations:

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”

Functions applicable only on string data [Link] => Delhi


type.:
• Capitalize
‘today is wednesday’.title()
• Title
Today Is Wednesday
• Upper
• Swapcase [Link] => DELHI
[Link]() => 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

Index() function also gives same result, but if any


character or substring not occurred then it gives error.
Basics of Python Programming
String function in python
“Today is friday”.endswith(“pqr”) =>False
“Today is friday”.startswith(“To”) =>True

Functions applicable only on string data


"Hello my name is {} i am {} years age".format("Aman",32)
type.
Output:
• Endswith/startswith 'Hello my name is Aman i am 32 years age’
• format
"Hello my name is {1} i am {0} years age".format("Aman",32)
Output:
'Hello my name is 32 i am Aman years age’

"Hello my name is {name} i am {Age} years age".format(name="Aman", Age


=32)
Output:
'Hello my name is aman i am 32 years age'
Basics of Python Programming
String function in python
"python512".isalnum()=>True
"python512$".isalnum()=>False
Functions used to ask question.
• isalnum "python".isalpha()=>True
• Isalpha "python2".isalpha()=>False
• Isdecimal
"50".isdigit() => True
• Isdigit
"50k".isdigit() =>False
• isidentifier
"50".isdecimal()=>True
"50.0".isdecimal()=>False

"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'

"i".join(['what else rema', 'n', 'ng ', 'n our course’])


'what else remaining in our course'

"/".join(['what', 'else', 'remaining', 'in', 'our', 'course’])


'what/else/remaining/in/our/course'
Basics of Python Programming
String function in python
"I am in mars".replace("mars","earth")
• Replace 'I am in earth'
Replace replaces the specified word.

• strip name = " Amit “


Strip removes the leading and trailing print("Hi",[Link]())
spaces.
Output: Hi Amit
Data Structure
List: List is a linear data structure. It can store heterogenous data.

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

L[0] Exclude last


element. L3[4][-1] L3[-1][0]
Output: 1 Output: 6 Output: 5
L[::-1]
L[4] L3[4][0] L3[-1][-1]
Output: [5,4,3,2,1]
Output: 5 Output: 5 Output: 6
Data Structure
Multi-dimensional List:
3D List:-
L4 = [[[1,2],[3,4]],[[5,6],[7,8]]]
Question: How to fetch 7 out of this list.
Solution:
x = L4[1]
X[1][0]
Output: 7
Or,
L4[1][1][0]
Output: 7
Data Structure
How to Edit.
L2=[1,2,3,4,5]
L = [1,2,3,4,5] L2[1:4] = [30,40,50,60,70]
L
L2
Output: [1, 2, 3, 4, 5]
Output: [1, 30, 40, 50, 60, 70, 5]
L[0] = 50
Output: [50, 2, 3, 4, 5]
Lists in python are
mutable.
L[-1] = 20
Output: [50, 2, 3, 4, 20]
Data Structure
L = [1,2,3,4,5]
[Link](100)
How to add. L
Output: [1,2,3,4,5,100]
[Link]("hello")
• append Output: [1, 2, 3, 4, 5, 'hello’]
• append function insert one
element at last either it is integer, [Link]([5,6])
list or string. L
Output: [1, 2, 3, 4, 5, [5, 6]]
Data Structure
L = [1,2,3,4,5]
[Link]([30,40,50])
How to add. L
Output: [1, 2, 3, 4, 5, 30, 40, 50]

• 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}

Delete last 4 element from list.


del L[-3:]
Data Structure
L = [1, 'hello', 2, 3, 4, 5]
How to delete.
[Link](‘hello’)
L
• Remove Output: [1, 2, 3, 4, 5]
• If we don’t know index of
element. But you know the
element exist in the list.
Data Structure
L=[1,2,3,4,5]
How to delete. [Link]()
L
• Pop Output: [1, 2, 3, 4]
• Pop delete the last element.
L1=[1,2,[3,4],[5,6]]
L1
[1, 2, [3, 4], [5, 6]]
[Link]()
L1
Output: [1, 2, [3, 4]]
Data Structure
How to delete. L=[1,2,3,4,5]
• Clear [Link]()
• It empty the list. L
Output: []
Data Structure
3. L = [1,2,3]
for i in L:
1. L = [1,2,3,4] print(i)
Operations on the list L1=[5,6,7,8] Output:
• Concatenation L+L1 1
• It concatenate the two list. Both list Output: [1, 2, 3, 4, 5, 6, 7, 8] 2
is not change. A new list is formed 3
by concatenation.
L1 = [1,2,3,[4,5]]
• Multiplication For i in L:
• Multiply the list by number. 2. L=[1,2,3]
print(i)
• Loop L Output:
• Loop can be used with list [1,2,3] 1
• Membership operation L*3 2
Output: [1, 2, 3, 1, 2, 3, 1, 2, 3
3] [4,5]

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:

Input: how much money you have ?


Output: How Much Money You have.
Data Structure
Operations on the list
Write a program to convert string like
this form:
string = "how much money you have. ?“
Input: how much money you have ? L=[]
Output: How Much Money You have. print([Link]())
for i in [Link]():
print([Link]())
[Link]([Link]())
L
print(" ".join(L))
Data Structure
Operations on the list
Write a program to fetch substring
from given list:
string = xyz@[Link]“
print(string[:[Link]("@")])
Input: xyz@[Link]
Output: fetch substring before @.
Or,

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 = ()

T2=(1,2,3,4,5) //Homogeneous tuple T5=(1) //Single item tuple


T2 T5
(1,2,3,4,5) 1
T6 = (“Hello”) //Single item tuple
T2=("Hello",2,3,4) T6
T2
“Hello”
('Hello', 2, 3, 4)
Type(T3)=>tuple
Type(T5)=>int
Single item tuple can be generated as follows.
Type(T6)=>string
T5 = (1,)=>type(T5) => tuple
T6 = (“Hello”,) =>type(T6) =>tuple
Data Structure
• There are different way to create tuple.

T6=tuple("git")
T6
type(T6) =>tuple

We can create tuple using list.


T7=tuple([1,2,3,4,5])
T7
(1, 2, 3, 4, 5)
type(T7)=>tuple
Data Structure
• Access tuple. T1[:3]
(1,2,3)
T1
(1,2,3,4)
T1[0]
1

T1[-1] T4=(1,2,3,(4,5),(7,8))
4 T4
T4[-1][0] => 7
Data Structure
• Edit tuple.

Tuple are not editable, i.e Tuples are


immutable like string.
We can not add new item in tuple.

Addition of new item in tuple is also not


possible.
Data Structure
• Delete 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.

So , because of hashing internal mechanism, duplicates are not allowed.


hash(“Hello”)
When you insert an element into s set, python compute the hash:
hash(2)
h = hash(element)
hash(3) Control go to the slot decided by that hash.
These hash value decide where the element is stored inside the If element is already there, python checks,
set.
existing_element == new_element.



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

If same hash and “==” returns True.


Then python treats it as a duplicate.
S3 = {1,1,2,2,3,3}
S3
{1,2,3}
Data Structure
• Sets doesn’t allow mutable data type.
• But you can use tuple in the set, because
S = {[1,2,3],”world”} tuple is immutable.

Traceback (most recent call last):


File "<pyshell#18>", line 1, in <module>
s4= {(1,2,3),"Hello"}
s4= {[1,2,3],"Hello"} s4
TypeError: unhashable type: 'list’
{'Hello', (1, 2, 3)}
What does hashable means in python ?
An object is hashable if:
1. It has a has value.
2. Its hash value never changes during its lifetime.

Only such objects can be used in:


• sets
• dictionary key
Data Structure
• How to access item in the Sets: • How to edit item in the Sets:

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

Address is same . Addition is possible.


Data Structure
• How to delete the Sets: s1 ={1,2,3,4,5}
1. del
s1
2. remove
3. pop {1, 2, 3, 4, 5}
[Link]()
del s2 1
del s2[0] //Not work, No indexing concept.

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}}

{'Name': 'Ajay', 'Gender': 'Male'}


D["Name"] = "Biploy" D4["Marks"]["Math"] = 48

D D4

{'Name': 'Biploy', 'Gender': 'Male’} {'Name': 'Vijay', 'College': 'GNIOT', 'Marks':


{'DS': 35, 'Hindi': 38, 'Math': 48}}

[Link](“Name”) can also be used to access


Name. but we can’t use it in 2-D dictionary.
Data Structure
D4
• How to add new key-value pair. {'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS':
35, 'Hindi': 38, 'Math': 48}}

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

In Python dictionary, the in operator checks only keys, not values.


Data Structure
D4
Function in Dictionary. {'Name': 'Vijay', 'College': 'GNIOT', 'Marks': {'DS':
35, 'Hindi': 38, 'Math': 48, 'Eng': 40}}

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

General Syntax: { expression for item in iterable if condition }

s = {x for x in range(5)}
print(s)
{0, 1, 2, 3, 4}

even = {x for x in range(10) if x % 2 == 0}


print(even)

{0, 2, 4, 6, 8}

lst = [3,3,5,5,6,6,7,7]

s1= {x for x in lst}


s1
{3, 5, 6, 7}
Data Structure
Tuple comprehension :There is not tuple comprehension in python.

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)

You might also like