SlideShare a Scribd company logo
Unit 3:-Data Structure in Python
• 3.1 List
a) Defining list , accessing value in list, deleting value in list, updating list
b) Basic list Operations
c) Built in List-functions
Defining list
Creating a list is as simple as putting different comma-separated
values between square brackets.
• # List of integers
• a = [1, 2, 3, 4, 5]
• # List of strings
• b = ['apple', 'banana', 'cherry']
• # Mixed data types
• c = ['PWP', 'MAD', 6, 20]
• print(a)
• print(b)
accessing value in list with index no
• S=“python”
• Print(s[0])----------p
• a = [10, 20, 30, 40, 50]
• # Access first element
• print(a[0])---------10
• # Access last element
• print(a[-1])-----------50
accessing value in list with Slicing
• list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']
• print(list1[2])
• print(list1[2:5])
• print(list1[3:])
• print(list1[-2])
• print(list1[-4:3])
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[-2:]
print(b)
c = a[:-3]
print(c)
d = a[-4:-1]
print(d)
e = a[-8:-1:2]
print(e)
# Get the entire list reverse using negative
step
b = a[::-1]
print(b)
my_list = [1, 2, 3, 4, 5]
print(my_list[-1:3:-1]) --> 5
print(my_list[1:3:-1])----- []
deleting value in list
• Lists in Python have various built-in methods to remove items such
as remove, pop, del and clear methods.
remove():-
• The remove() method deletes the first occurrence of a specified value in the list.
If multiple items have the same value, only the first match is removed.
• Syntax remove(value only)
• a = [10, 20, 30, 40, 50]
• a.remove(30)
• print(a) ---------- [10, 20, 40, 50]
Pop(): The pop() method can be used to remove an element from a list based
on its index and it also returns the removed element.
• a = [10, 20, 30, 40, 50]
val = a.pop(1)
print(a)
print("Removed Item:", val)
Output:-
[10, 30, 40, 50]
Removed Item: 20
del():The del statement can remove elements from a list by
specifying their index or a range of indices.
• Example:
• a = [10, 20, 30, 40, 50,60,70]
• del a[2]
• print(a)----------Output:[10, 20, 40, 50]
• del a[1:4]
• print(a)---------- [10, 50, 60, 70]
Clear():-If we want to remove all elements from a list then we can use
the clear() method. and return empty list
a = [10, 20, 30, 40]
a.clear()
print(a)------------------output:-[]
Updating list
• To change the value of a specific item, refer to the index number
• a = ["apple", "banana", "cherry"]
• a[1] = " pineapple "
• print(a)
#Change a Range of Item Values
b = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
b[1:3] = [“pineapple", "watermelon"]
print(b)
• Python List Operations
• Consider a List l1 = [1, 2, 3, 4] and l2 = [5, 6, 7, 8]
1.Repetition:- The repetition operator enables the list elements to be repeated multiple times.
• EX- print(L1*2 )-------------------[1, 2, 3, 4, 1, 2, 3, 4]
2. Concatenation:- It concatenates the list mentioned on either side of the operator.
• Ex- print(l1+l2)----------------------- [1, 2, 3, 4, 5, 6, 7, 8]
3. Membership:- It returns true if a particular item exists in a particular list otherwise false.
• Ex- print(2 in l1) ---------------True.
4. Iteration:- The for loop is used to iterate over the list elements.
• for i in l1:
print(i)
• Output
1
2
3
4
5. Length It is used to get the length of the list
• Print( len(l1)) ---------------------------- 4
Built in function in list
• Python has a set of built-in methods that you can use on lists
1 dir():-
We can see the built in methods using the dir() function
Ex:-print(dir(list))
2.help() :- The Python help() function is used to display the documentation of modules,
functions
EX:-Print(help(list.append))
3. append():-The Python List append() method is used for appending and adding elements to the
end of the Python List.
syntax:- append(add element name)
list1=[1,2,3,4,5]
Print(list.appent(12))---------------[1,2,3,4,5,12]
4.count() :
• Python List count() :- this method returns the count of how many times a given object occurs
in a List using python.
• Syntax: list_name.count(object)
• List1=[1,2,3,4,5,1,2,5,6,3]
• Print(List1.count(2))----------------output:-2
5. insert():
• Inserting an element at a particular place into a list is one of the essential
operations when working with lists
• Syntax:- list_name.insert (index, element)
• A=[1,2,3,4,]
• Print(A.insert(2,”hiii”)----------output A[1,2,hiii,4]
6. reverse():
• Python List reverse() is an inbuilt method in the Python language that
reverses objects of the list.
• Syntax :list_name.reverse ()
A=[1,2,3,4,5]
print(A.reverse())
7.sort():
• Python list sort() function can be used to sort List with Python in ascending,
descending order
• Syntax :List_name.sort ()
• A=[10,5,7,1,2,3,4,5]
• Print(A.sort())
• Print(a.sort(reverse=True))
8.len():-The Python List len() method is used to compute the size of a Python List
• Syntax:- len(list)
• Print(len(A))
Tuple:
a)Creating tuple, Accessing value in tuple , deleting value in tuple,
updating value in tuple
b) Basic tuple operations
c) built in tuple functions
Tuple:
An object of tuple allows us to store multiple values of same type or different type or both types.
An object of tuple type allows us to organize both unique and duplicate values.
The elements of tuple must be enclosed within Braces ( ) and the values must be separated by comma (,)
• Creating tuple:
• tuple of integers
• a = (1, 2, 3, 4, 5,1)
• # of tuple strings
• b = ('apple', 'banana', 'cherry‘)
• # Mixed data types
• c = (“PWP”, “MAD”, 6, 20, “ PWP”)
• print(a)
• print(b)
• print(c)
Accessing Tuple Elements by Index
• my_tuple = ('apple', 'banana', 'cherry', 1, 2, 3)
• print(my_tuple[0])
• print(my_tuple[-1])
• print(my_tuple[3])
• print(my_tuple[5])
• print(my_tuple[-6])
• print(my_tuple[2])
Accessing Tuple Elements by Slicing
• tuple4 = (“OOP", “DSU", 21, 69.75,”MAD”)
Print(tuple4[1:4])
Print(tuple4[-1:4:-1])
Print(tuple4[::-1])
Print(tuple4[:])
Print(tuple4[2:4:1])
Print(tuple4[4:1])
Updating tuple:-
• Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called
• But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple
• x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Deleting Tuple
• Tuples are immutable, you cannot delete individual elements from a tuple
• But you can delete an entire tuple using the del keyword
• If you try to print a tuple after deleting it, you will receive an error because the
tuple no longer exists.
• Ex:
• thistuple = ("apple", "banana", "cherry")
• del thistuple
• print(thistuple) #this will raise an error because the tuple no longer exists
Python Tuple Operations
• Consider a tuple l1 = (1, 2, 3, 4) and l2 = (5, 6, 7, 8)
1.Repetition:- The repetition operator enables the tuple elements to be repeated
multiple times.
• EX- a=l1*2
• print(a)-------------------(1, 2, 3, 4, 1, 2, 3, 4)
2. Concatenation:- It concatenates the list mentioned on either side of the
operator.
• Ex- b=l1+l2
• print(b)----------------------- [1, 2, 3, 4, 5, 6, 7, 8]
l1 = (1, 2, 3, 4)
3. Membership:- It returns true if a particular item exists in a particular tuple otherwise
false.
• Ex- print(2 in l1) ---------------True.
4. Iteration:- The for loop is used to iterate over the tuple elements.
• for i in l1:
print(i)
• Output
1
2
3
4
5. Length It is used to get the length of the tuple
• Print( len(l1)) ---------------------------- 4
Tuple built in function
1. The sorted() Function
• This method takes a tuple as an input and returns a sorted list as an output. Moreover, it does
not make any changes to the original tuple
• >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
• >>> sorted(tup)
• [1, 2, 2.4, 3, 4, 22, 45, 56, 890]
2. min():-min(): gives the smallest element in the tuple as an output. Hence, the name is min().
• >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
• >>> max(tup)-------------------------output:-890
3. max(): gives the largest element in the tuple as an output. Hence, the name is
max()
• >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
• >>> max(tup)----------------------output:-890
4. Sum():-gives the sum of the elements present in the tuple as an output
• >>> tup = (22, 3, 45, 4, 2, 56, 890, 1)
• >>> sum(tup)---------------------------1023
Set
a) Accessing values in set, deleting values in set, Updating sets
b) Basic set operations
c) Built-in set functions
• Sets are used to store multiple items in a single variable.
• Sets do not support indexing
• A set is a collection which is unordered, unchangeable, and unindexed
• Unordered means that the items in a set do not have a defined order
• The elements of the set can not be duplicate.
• The elements of the python set must be immutable.
• The values False ,True and 0,1 are considered the same value in sets,
and are treated as duplicates
• Set declared with curly braces
Creating a set
• Example 1:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"}
print(Days)
Accessing set values:we access value from set using for loop
• Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
for i in Days:
print(i)
• Output:
• Friday
• Tuesday
• Monday
• Saturday
• Thursday
• Sunday
• Wednesday
Updating set
• Removing items from the set
• Following methods used to remove the items from the set
• 1. discard
• 2. remove
• 3. pop
discard() method
• discard() method Python provides discard() method which can be used to remove
the items from the set.
• Months ={ "January","February", "March", "April", "May", "June“}
• Months.discard("January");
• Months.discard("May");
• Output:-
• {'February', 'March', 'April', 'June'}
remove() method: method Python provides remove() method which
can be used to remove the items from the set
• thisset = {"apple", "banana", "cherry"}
• thisset.remove("banana")
• print(thisset)
• output:
• {"apple”, "cherry"}
difference between remove and discard
• The discard() method removes the specified item from the set. This
method is different from the remove() method, because the remove()
method will raise an error if the specified item does not exist, and the
discard() method will not
pop() method
• the pop(), method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets
removed
• Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed
• thisset = {"apple", "banana", "cherry"}
• x = thisset.pop()
• print(x)
• print(thisset)
• output:
• apple
• {'cherry', 'banana'
delete the set
• The del keyword will delete the set completely:
• thisset = {"apple", "banana", "cherry"}
• del thisset
• print(thisset)
• output:
• File "demo_set_del.py", line 5, in print(thisset) #this will raise an error because the set no
longer exists NameError: name 'thisset' is not defined
Adding items to the set
• add() method
• update() method.
add() method
• Python provides the add() method which can be used to add some particular
item to the set
• Months = {"January","February", "March", "April", "May", "June“}
• Months.add("July");
• Months.add("August");
• print(Months)
• output:
• {'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
update() method.
Python provides the update() method which can be used to add
multiple element to the set
• Months = {"January","February", "March", "April", "May", "June“}
Months.update(["July","August","September","October“]);
• print(Months)
• output:
• {'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Basic set operation
1. Union
2. Intersection
3. difference
4. symmetric difference)
In Python, below quick operands can be used for different operations
• | for union.
• & for intersection.
• – for difference
• ^ for symmetric difference
• Set union:-
• The union of two sets is the set of all the elements of both the sets without
duplicates. You can use the union() method or the | operator
• Example-1:-
first_set = {1, 2, 3}
second_set = {3, 4, 5}
• first_set.union(second_set)----------------------------{1, 2, 3, 4, 5}
• Example-2:-
• # using the `|` operator
• first_set | second_set -----------------------------------------{1, 2, 3, 4, 5}
Set intersection:-The intersection of two sets is the set of all the common
elements of both the sets. You can use the intersection() method of the &
operator to find the intersection of a Python set.
• first_set = {1, 2, 3, 4, 5, 6}
• second_set = {4, 5, 6, 7, 8, 9}
• first_set.intersection(second_set)------------------------{4, 5, 6}
# using the `&` operator
• first_set & second_set---------------------{4, 5, 6}
Set Difference:-
The difference between two sets is the set of all the elements in first set that are
not present in the second set. You would use the difference() method or the -
operator to achieve this in Python.
• first_set = {1, 2, 3, 4, 5, 6}
• second_set = {4, 5, 6, 7, 8, 9}
• first_set.difference(second_set)---------------------{1, 2, 3}
• # using the `-` operator
• first_set - second_set {1, 2, 3}
• second_set - first_set---------------------------------{8, 9, 7}
• Set Symmetric Difference
• The symmetric difference between two sets is the set of all the elements that
are either in the first set or the second set but not in both
• You have the choice of using either the symmetric_difference() method or the ^
operator to do this in Python
• first_set = {1, 2, 3, 4, 5, 6}
• second_set = {4, 5, 6, 7, 8, 9}
• first_set.symmetric_difference(second_set)---------------------{1, 2, 3, 7, 8, 9}
• # using the `^` operator
• first_set ^ second_set------------------------{1, 2, 3, 7, 8, 9}
Set built in function
• 1add()
• 2 update()
• 3 discard()
• 4 remove()
• 5 pop()
• 6 union()
• 7 intersection()
• 8 difference()
• 9 symmetric_difference()
• 10 del
• 11 clear()
Dictionary
• Dictionary is used to implement the key-value pair in python. The keys are the
immutable python object, i.e., Numbers, string or tuple
• Python dictionaries are mutable but key are immutable
• Creating the dictionary
• The dictionary can be created by using multiple key-value pairs enclosed with the
curly brackets {} and separated by the colon (:).
• The collections of the key-value pairs are enclosed within the curly braces {}.
• The syntax to define the dictionary is given below.
• Dict = {"Name": "Ayush","Age": 22}
Accessing the dictionary values
• Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
• print("printing Employee data .... ")
• print("Name :",Employee["Name"])
• print("Age : ",Employee["Age"])
• print("Salary : ",Employee["salary"])
• print("Company : ", Employee["Company"]
Updating dictionary values
• my_dict = {'name':'MMP', 'age': 26}
• # update value
• my_dict['age'] = 27
• print(my_dict)
• Output: {'age': 27, 'name': 'MMP‘}
• # add item
• my_dict['address'] = 'Downtown‘
• print(my_dict)
• Output: {'address': 'Downtown', 'age': 27, 'name': 'MMP'}
Deleting elements using del keyword
• Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
• del Employee["Name"]
• del Employee["Company"]
• Output: {'Age': 29, 'salary': 25000}
Dictionary Operations :-
Below is a list of common dictionary operations:
• create an empty dictionary
x = {}
• create a three items dictionary
x = {"one":1, "two":2, "three":3}
• access an element
x['two']
print(x)-------------------------{2}
• get a list of all the keys
x.keys()
print(x)-------------------------{one,two, three}
• get a list of all the values
x.values()
print(x)------------------------------{1,2,3}
x = {"one":1, "two":2, "three":3}
• add an element
x["four"]=4 ------------------------------- {"one":1, "two":2, "three":3,”four”:4}
change an element
x["one"] = “hiiii“---------------------{"one":”hiii”, "two":2, "three":3,”four”:4}
• delete an element
del x["four"]----------------------{"one":”hiii”, "two":2, "three":3}
remove all items
x.clear() ------------------------------{}
x = {"one":1, "two":2, "three":3}
• looping over values
• for i in x.values():
print(i)
Output
1
2
3
• looping over keys
• for I in x.keys():
• Print( i)
• Output:_
One
two
three

More Related Content

Similar to Programming with Python_Unit-3-Notes.pptx (20)

PPT
Programming in Python Lists and its methods .ppt
Dr. Jasmine Beulah Gnanadurai
 
PPTX
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
usha raj
 
PDF
python_avw - Unit-03.pdf
AshaWankar1
 
PPTX
Python data structures
kalyanibedekar
 
PPTX
Python - List, Dictionaries, Tuples,Sets
Mohan Arumugam
 
PPTX
python ..... _
swati463221
 
PPTX
updated_list.pptx
Koteswari Kasireddy
 
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
PPTX
Python Collections
sachingarg0
 
PDF
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
PPTX
MODULE-2.pptx
ASRPANDEY
 
PPTX
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
meganathan162007
 
DOC
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
PPTX
tupple.pptx
satyabratPanda2
 
PDF
Python lecture 04
Tanwir Zaman
 
PPTX
PROBLEM SOLVING AND PYTHON PROGRAMMING PPT
MulliMary
 
PPT
UNIT III_Python Programming_aditya COllege
Ramanamurthy Banda
 
PPTX
PYTHON.pptx
prateeksingh606762
 
PDF
Python - Lecture 4
Ravi Kiran Khareedi
 
PPTX
PYTHON.pptx
rohithprakash16
 
Programming in Python Lists and its methods .ppt
Dr. Jasmine Beulah Gnanadurai
 
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
usha raj
 
python_avw - Unit-03.pdf
AshaWankar1
 
Python data structures
kalyanibedekar
 
Python - List, Dictionaries, Tuples,Sets
Mohan Arumugam
 
python ..... _
swati463221
 
updated_list.pptx
Koteswari Kasireddy
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Python Collections
sachingarg0
 
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
MODULE-2.pptx
ASRPANDEY
 
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
meganathan162007
 
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
tupple.pptx
satyabratPanda2
 
Python lecture 04
Tanwir Zaman
 
PROBLEM SOLVING AND PYTHON PROGRAMMING PPT
MulliMary
 
UNIT III_Python Programming_aditya COllege
Ramanamurthy Banda
 
PYTHON.pptx
prateeksingh606762
 
Python - Lecture 4
Ravi Kiran Khareedi
 
PYTHON.pptx
rohithprakash16
 

Recently uploaded (20)

PPTX
drones for disaster prevention response.pptx
NawrasShatnawi1
 
PDF
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
PPTX
NEUROMOROPHIC nu iajwojeieheueueueu.pptx
knkoodalingam39
 
PDF
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
PPTX
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PDF
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
PPTX
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PPTX
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
PDF
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
PPTX
REINFORCEMENT AS CONSTRUCTION MATERIALS.pptx
mohaiminulhaquesami
 
PDF
BioSensors glucose monitoring, cholestrol
nabeehasahar1
 
PPTX
Structural Functiona theory this important for the theorist
cagumaydanny26
 
PPTX
Presentation on Foundation Design for Civil Engineers.pptx
KamalKhan563106
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
UNIT-4-FEEDBACK AMPLIFIERS AND OSCILLATORS (1).pdf
Sridhar191373
 
PPTX
ISO/IEC JTC 1/WG 9 (MAR) Convenor Report
Kurata Takeshi
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
drones for disaster prevention response.pptx
NawrasShatnawi1
 
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
NEUROMOROPHIC nu iajwojeieheueueueu.pptx
knkoodalingam39
 
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
REINFORCEMENT AS CONSTRUCTION MATERIALS.pptx
mohaiminulhaquesami
 
BioSensors glucose monitoring, cholestrol
nabeehasahar1
 
Structural Functiona theory this important for the theorist
cagumaydanny26
 
Presentation on Foundation Design for Civil Engineers.pptx
KamalKhan563106
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
UNIT-4-FEEDBACK AMPLIFIERS AND OSCILLATORS (1).pdf
Sridhar191373
 
ISO/IEC JTC 1/WG 9 (MAR) Convenor Report
Kurata Takeshi
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Ad

Programming with Python_Unit-3-Notes.pptx

  • 1. Unit 3:-Data Structure in Python • 3.1 List a) Defining list , accessing value in list, deleting value in list, updating list b) Basic list Operations c) Built in List-functions
  • 2. Defining list Creating a list is as simple as putting different comma-separated values between square brackets. • # List of integers • a = [1, 2, 3, 4, 5] • # List of strings • b = ['apple', 'banana', 'cherry'] • # Mixed data types • c = ['PWP', 'MAD', 6, 20] • print(a) • print(b)
  • 3. accessing value in list with index no • S=“python” • Print(s[0])----------p • a = [10, 20, 30, 40, 50] • # Access first element • print(a[0])---------10 • # Access last element • print(a[-1])-----------50
  • 4. accessing value in list with Slicing • list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP'] • print(list1[2]) • print(list1[2:5]) • print(list1[3:]) • print(list1[-2]) • print(list1[-4:3])
  • 5. a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = a[-2:] print(b) c = a[:-3] print(c) d = a[-4:-1] print(d) e = a[-8:-1:2] print(e) # Get the entire list reverse using negative step b = a[::-1] print(b) my_list = [1, 2, 3, 4, 5] print(my_list[-1:3:-1]) --> 5 print(my_list[1:3:-1])----- []
  • 6. deleting value in list • Lists in Python have various built-in methods to remove items such as remove, pop, del and clear methods. remove():- • The remove() method deletes the first occurrence of a specified value in the list. If multiple items have the same value, only the first match is removed. • Syntax remove(value only) • a = [10, 20, 30, 40, 50] • a.remove(30) • print(a) ---------- [10, 20, 40, 50]
  • 7. Pop(): The pop() method can be used to remove an element from a list based on its index and it also returns the removed element. • a = [10, 20, 30, 40, 50] val = a.pop(1) print(a) print("Removed Item:", val) Output:- [10, 30, 40, 50] Removed Item: 20
  • 8. del():The del statement can remove elements from a list by specifying their index or a range of indices. • Example: • a = [10, 20, 30, 40, 50,60,70] • del a[2] • print(a)----------Output:[10, 20, 40, 50] • del a[1:4] • print(a)---------- [10, 50, 60, 70]
  • 9. Clear():-If we want to remove all elements from a list then we can use the clear() method. and return empty list a = [10, 20, 30, 40] a.clear() print(a)------------------output:-[]
  • 10. Updating list • To change the value of a specific item, refer to the index number • a = ["apple", "banana", "cherry"] • a[1] = " pineapple " • print(a) #Change a Range of Item Values b = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] b[1:3] = [“pineapple", "watermelon"] print(b)
  • 11. • Python List Operations • Consider a List l1 = [1, 2, 3, 4] and l2 = [5, 6, 7, 8] 1.Repetition:- The repetition operator enables the list elements to be repeated multiple times. • EX- print(L1*2 )-------------------[1, 2, 3, 4, 1, 2, 3, 4] 2. Concatenation:- It concatenates the list mentioned on either side of the operator. • Ex- print(l1+l2)----------------------- [1, 2, 3, 4, 5, 6, 7, 8] 3. Membership:- It returns true if a particular item exists in a particular list otherwise false. • Ex- print(2 in l1) ---------------True. 4. Iteration:- The for loop is used to iterate over the list elements. • for i in l1: print(i) • Output 1 2 3 4 5. Length It is used to get the length of the list • Print( len(l1)) ---------------------------- 4
  • 12. Built in function in list • Python has a set of built-in methods that you can use on lists 1 dir():- We can see the built in methods using the dir() function Ex:-print(dir(list))
  • 13. 2.help() :- The Python help() function is used to display the documentation of modules, functions EX:-Print(help(list.append)) 3. append():-The Python List append() method is used for appending and adding elements to the end of the Python List. syntax:- append(add element name) list1=[1,2,3,4,5] Print(list.appent(12))---------------[1,2,3,4,5,12] 4.count() : • Python List count() :- this method returns the count of how many times a given object occurs in a List using python. • Syntax: list_name.count(object) • List1=[1,2,3,4,5,1,2,5,6,3] • Print(List1.count(2))----------------output:-2
  • 14. 5. insert(): • Inserting an element at a particular place into a list is one of the essential operations when working with lists • Syntax:- list_name.insert (index, element) • A=[1,2,3,4,] • Print(A.insert(2,”hiii”)----------output A[1,2,hiii,4] 6. reverse(): • Python List reverse() is an inbuilt method in the Python language that reverses objects of the list. • Syntax :list_name.reverse () A=[1,2,3,4,5] print(A.reverse())
  • 15. 7.sort(): • Python list sort() function can be used to sort List with Python in ascending, descending order • Syntax :List_name.sort () • A=[10,5,7,1,2,3,4,5] • Print(A.sort()) • Print(a.sort(reverse=True)) 8.len():-The Python List len() method is used to compute the size of a Python List • Syntax:- len(list) • Print(len(A))
  • 16. Tuple: a)Creating tuple, Accessing value in tuple , deleting value in tuple, updating value in tuple b) Basic tuple operations c) built in tuple functions
  • 17. Tuple: An object of tuple allows us to store multiple values of same type or different type or both types. An object of tuple type allows us to organize both unique and duplicate values. The elements of tuple must be enclosed within Braces ( ) and the values must be separated by comma (,) • Creating tuple: • tuple of integers • a = (1, 2, 3, 4, 5,1) • # of tuple strings • b = ('apple', 'banana', 'cherry‘) • # Mixed data types • c = (“PWP”, “MAD”, 6, 20, “ PWP”) • print(a) • print(b) • print(c)
  • 18. Accessing Tuple Elements by Index • my_tuple = ('apple', 'banana', 'cherry', 1, 2, 3) • print(my_tuple[0]) • print(my_tuple[-1]) • print(my_tuple[3]) • print(my_tuple[5]) • print(my_tuple[-6]) • print(my_tuple[2])
  • 19. Accessing Tuple Elements by Slicing • tuple4 = (“OOP", “DSU", 21, 69.75,”MAD”) Print(tuple4[1:4]) Print(tuple4[-1:4:-1]) Print(tuple4[::-1]) Print(tuple4[:]) Print(tuple4[2:4:1]) Print(tuple4[4:1])
  • 20. Updating tuple:- • Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called • But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple • x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x)
  • 21. Deleting Tuple • Tuples are immutable, you cannot delete individual elements from a tuple • But you can delete an entire tuple using the del keyword • If you try to print a tuple after deleting it, you will receive an error because the tuple no longer exists. • Ex: • thistuple = ("apple", "banana", "cherry") • del thistuple • print(thistuple) #this will raise an error because the tuple no longer exists
  • 22. Python Tuple Operations • Consider a tuple l1 = (1, 2, 3, 4) and l2 = (5, 6, 7, 8) 1.Repetition:- The repetition operator enables the tuple elements to be repeated multiple times. • EX- a=l1*2 • print(a)-------------------(1, 2, 3, 4, 1, 2, 3, 4) 2. Concatenation:- It concatenates the list mentioned on either side of the operator. • Ex- b=l1+l2 • print(b)----------------------- [1, 2, 3, 4, 5, 6, 7, 8]
  • 23. l1 = (1, 2, 3, 4) 3. Membership:- It returns true if a particular item exists in a particular tuple otherwise false. • Ex- print(2 in l1) ---------------True. 4. Iteration:- The for loop is used to iterate over the tuple elements. • for i in l1: print(i) • Output 1 2 3 4 5. Length It is used to get the length of the tuple • Print( len(l1)) ---------------------------- 4
  • 24. Tuple built in function 1. The sorted() Function • This method takes a tuple as an input and returns a sorted list as an output. Moreover, it does not make any changes to the original tuple • >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) • >>> sorted(tup) • [1, 2, 2.4, 3, 4, 22, 45, 56, 890] 2. min():-min(): gives the smallest element in the tuple as an output. Hence, the name is min(). • >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) • >>> max(tup)-------------------------output:-890
  • 25. 3. max(): gives the largest element in the tuple as an output. Hence, the name is max() • >>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) • >>> max(tup)----------------------output:-890 4. Sum():-gives the sum of the elements present in the tuple as an output • >>> tup = (22, 3, 45, 4, 2, 56, 890, 1) • >>> sum(tup)---------------------------1023
  • 26. Set a) Accessing values in set, deleting values in set, Updating sets b) Basic set operations c) Built-in set functions
  • 27. • Sets are used to store multiple items in a single variable. • Sets do not support indexing • A set is a collection which is unordered, unchangeable, and unindexed • Unordered means that the items in a set do not have a defined order • The elements of the set can not be duplicate. • The elements of the python set must be immutable. • The values False ,True and 0,1 are considered the same value in sets, and are treated as duplicates • Set declared with curly braces
  • 28. Creating a set • Example 1: Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} print(Days)
  • 29. Accessing set values:we access value from set using for loop • Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} for i in Days: print(i) • Output: • Friday • Tuesday • Monday • Saturday • Thursday • Sunday • Wednesday
  • 30. Updating set • Removing items from the set • Following methods used to remove the items from the set • 1. discard • 2. remove • 3. pop
  • 31. discard() method • discard() method Python provides discard() method which can be used to remove the items from the set. • Months ={ "January","February", "March", "April", "May", "June“} • Months.discard("January"); • Months.discard("May"); • Output:- • {'February', 'March', 'April', 'June'}
  • 32. remove() method: method Python provides remove() method which can be used to remove the items from the set • thisset = {"apple", "banana", "cherry"} • thisset.remove("banana") • print(thisset) • output: • {"apple”, "cherry"}
  • 33. difference between remove and discard • The discard() method removes the specified item from the set. This method is different from the remove() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not
  • 34. pop() method • the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed • Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed • thisset = {"apple", "banana", "cherry"} • x = thisset.pop() • print(x) • print(thisset) • output: • apple • {'cherry', 'banana'
  • 35. delete the set • The del keyword will delete the set completely: • thisset = {"apple", "banana", "cherry"} • del thisset • print(thisset) • output: • File "demo_set_del.py", line 5, in print(thisset) #this will raise an error because the set no longer exists NameError: name 'thisset' is not defined
  • 36. Adding items to the set • add() method • update() method.
  • 37. add() method • Python provides the add() method which can be used to add some particular item to the set • Months = {"January","February", "March", "April", "May", "June“} • Months.add("July"); • Months.add("August"); • print(Months) • output: • {'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
  • 38. update() method. Python provides the update() method which can be used to add multiple element to the set • Months = {"January","February", "March", "April", "May", "June“} Months.update(["July","August","September","October“]); • print(Months) • output: • {'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
  • 39. Basic set operation 1. Union 2. Intersection 3. difference 4. symmetric difference)
  • 40. In Python, below quick operands can be used for different operations • | for union. • & for intersection. • – for difference • ^ for symmetric difference
  • 41. • Set union:- • The union of two sets is the set of all the elements of both the sets without duplicates. You can use the union() method or the | operator • Example-1:- first_set = {1, 2, 3} second_set = {3, 4, 5} • first_set.union(second_set)----------------------------{1, 2, 3, 4, 5} • Example-2:- • # using the `|` operator • first_set | second_set -----------------------------------------{1, 2, 3, 4, 5}
  • 42. Set intersection:-The intersection of two sets is the set of all the common elements of both the sets. You can use the intersection() method of the & operator to find the intersection of a Python set. • first_set = {1, 2, 3, 4, 5, 6} • second_set = {4, 5, 6, 7, 8, 9} • first_set.intersection(second_set)------------------------{4, 5, 6} # using the `&` operator • first_set & second_set---------------------{4, 5, 6}
  • 43. Set Difference:- The difference between two sets is the set of all the elements in first set that are not present in the second set. You would use the difference() method or the - operator to achieve this in Python. • first_set = {1, 2, 3, 4, 5, 6} • second_set = {4, 5, 6, 7, 8, 9} • first_set.difference(second_set)---------------------{1, 2, 3} • # using the `-` operator • first_set - second_set {1, 2, 3} • second_set - first_set---------------------------------{8, 9, 7}
  • 44. • Set Symmetric Difference • The symmetric difference between two sets is the set of all the elements that are either in the first set or the second set but not in both • You have the choice of using either the symmetric_difference() method or the ^ operator to do this in Python • first_set = {1, 2, 3, 4, 5, 6} • second_set = {4, 5, 6, 7, 8, 9} • first_set.symmetric_difference(second_set)---------------------{1, 2, 3, 7, 8, 9} • # using the `^` operator • first_set ^ second_set------------------------{1, 2, 3, 7, 8, 9}
  • 45. Set built in function • 1add() • 2 update() • 3 discard() • 4 remove() • 5 pop() • 6 union() • 7 intersection() • 8 difference() • 9 symmetric_difference() • 10 del • 11 clear()
  • 46. Dictionary • Dictionary is used to implement the key-value pair in python. The keys are the immutable python object, i.e., Numbers, string or tuple • Python dictionaries are mutable but key are immutable • Creating the dictionary • The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {} and separated by the colon (:). • The collections of the key-value pairs are enclosed within the curly braces {}. • The syntax to define the dictionary is given below. • Dict = {"Name": "Ayush","Age": 22}
  • 47. Accessing the dictionary values • Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} • print("printing Employee data .... ") • print("Name :",Employee["Name"]) • print("Age : ",Employee["Age"]) • print("Salary : ",Employee["salary"]) • print("Company : ", Employee["Company"]
  • 48. Updating dictionary values • my_dict = {'name':'MMP', 'age': 26} • # update value • my_dict['age'] = 27 • print(my_dict) • Output: {'age': 27, 'name': 'MMP‘} • # add item • my_dict['address'] = 'Downtown‘ • print(my_dict) • Output: {'address': 'Downtown', 'age': 27, 'name': 'MMP'}
  • 49. Deleting elements using del keyword • Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} • del Employee["Name"] • del Employee["Company"] • Output: {'Age': 29, 'salary': 25000}
  • 50. Dictionary Operations :- Below is a list of common dictionary operations: • create an empty dictionary x = {} • create a three items dictionary x = {"one":1, "two":2, "three":3} • access an element x['two'] print(x)-------------------------{2} • get a list of all the keys x.keys() print(x)-------------------------{one,two, three} • get a list of all the values x.values() print(x)------------------------------{1,2,3}
  • 51. x = {"one":1, "two":2, "three":3} • add an element x["four"]=4 ------------------------------- {"one":1, "two":2, "three":3,”four”:4} change an element x["one"] = “hiiii“---------------------{"one":”hiii”, "two":2, "three":3,”four”:4} • delete an element del x["four"]----------------------{"one":”hiii”, "two":2, "three":3} remove all items x.clear() ------------------------------{}
  • 52. x = {"one":1, "two":2, "three":3} • looping over values • for i in x.values(): print(i) Output 1 2 3 • looping over keys • for I in x.keys(): • Print( i) • Output:_ One two three