0% found this document useful (0 votes)
24 views52 pages

PWP_Unit-3-Notes

Unit 3 covers data structures in Python, focusing on lists, tuples, and sets. It details how to create, access, update, and delete elements in these structures, along with basic operations and built-in functions. The document provides examples and syntax for each operation, emphasizing the differences between methods like remove and discard in sets.

Uploaded by

raj373249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views52 pages

PWP_Unit-3-Notes

Unit 3 covers data structures in Python, focusing on lists, tuples, and sets. It details how to create, access, update, and delete elements in these structures, along with basic operations and built-in functions. The document provides examples and syntax for each operation, emphasizing the differences between methods like remove and discard in sets.

Uploaded by

raj373249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

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] # Get the entire list reverse using negative
step
b = a[-2:] b = a[::-1]
print(b) print(b)

c = a[:-3] my_list = [1, 2, 3, 4, 5]


print(c) print(my_list[-1:3:-1]) --> 5

d = a[-4:-1] print(my_list[1:3:-1])----- []
print(d)

e = a[-8:-1:2]
print(e)
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
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
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

You might also like