PWP Unit 3
PWP Unit 3
UNIT III
DATA STRUCTURES IN PYTHON
Lists :
Lists are used to store multiple items in a single variable.
A list can be defined as a collection of values or items of different
types.
Lists are created using square brackets [ ] and the items in the list
are separated with the comma (,).
List is a collection which is ordered and changeable. Allows
duplicate members.
Example :
1. List1=[1,2,3,4,5]
2. List2=[1,”India”2.5,”Japan”]
3. List3=[“apple”,”mango”,”orange”]
Accessing List :
List items are indexed and you can access them by referring to the
index number.
The elements of the list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1.
The first element of the list is stored at the 0th index, the second
element of the list is stored at the 1st index, and so on.
Example :
Fruits=["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
List[0]=apple
List[1]=banana
List[2]=cherry
List[3]=orange
List[4]=kiwi
List[5]=melon
List[6]=mango
Print(Fruits[:]})
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
Print(Fruits[1:])
["banana", "cherry", "orange", "kiwi", "melon", "mango"]
Print(Fruits[1:4])
[ "banana", "cherry", "orange"]
Print(Fruits[2:6])
[ "cherry", "orange", "kiwi", "melon"]
Print(Fruits[:3])
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
- -1 refers to the last item, -2 refers to the second last item etc.
Example :
List1=[1,2,3,4,5]
Print(List1[-1])
Output :
List1=[5]
Range of Indexes :
- When specifying a range, the return value will be a new list with
the specified items.
Example :
List1=[1,2,3,4,5,6]
Print(List1[2:5])
Output :
List1=[3,4,5]
Lists are the most versatile data structures in python since they are
immutable and their values can be updated by using the slice and
assignment operator.
Example 1 :
List = [1, 2, 3, 4, 5, 6]
print(List)
Output :[1, 2, 3, 4, 5, 6]
List[2] = 10;
print(List)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Example 2 :
Change the second and third value by replacing it with one value:
list = ["apple", "banana", "cherry"]
list[1:3] = ["watermelon"]
print(list)
The list elements can also be deleted by using the del keyword. Python
also provides us the remove() method , if we do not know which
element is to be deleted from the list.
List = [0,1,2,3,4]
print(List)
Output: [0, 1, 2, 3, 4]
del List[0]
print(List)
Output: [1, 2, 3, 4]
List = [0,1,2,3,4]
print(List)
Output: [0, 1, 2, 3, 4]
del List[0]
print(List)
Output : [ 1, 2 , 3 , 4 ]
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
The clear() method empties the list, The list still remains, but it
has nocontent.
Output: [ ]
Copy a List
- You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made
in list2.
- There are ways to make a copy, one way is to use the built-in List method copy().
print(mylist)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Functions Description
cmp(list1, It compares the elements of both the lists.
list2)
len(list) It is used to calculate the length of the list.
max(list) It returns the maximum element of the list.
min(list) It returns the minimum element of the list.
list(seq) It converts any sequence to the list.
Sum() It returns the sum of values in list.
Tuple :
Python Tuple is used to store the sequence of immutable python
objects.
Tuple is immutable and the value of the items stored in the tuple
cannot be changed.
A tuple can be written as the collection of elements, separated by
commas with the round brackets.
Accessing Tuple :
Tuple = (1,2,3,4,5,6)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Tuple[0]=1
Tuple[1]=2
Tuple[2]=3
Tuple[3]=4
Tuple[4]=5
Tuple[5]=6
Tuple[0:] = (1,2,3,4,5,6)
Tuple[:] = (1,2,3,4,5,6)
Tuple[2:4] = (3,4)
Tuple[1:3] = (2,3)
Tuple[:4] = (1,2,3,4)
The tuple items can not be deleted by using the del keyword as tuples
are immutable. To delete an entire tuple, we can use the del keyword
with the tuple name
Example :
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1
print(tuple1)
Updating values in tuple :
Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
Conut() :
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Index ( ) :
The tuple index() method helps us to find the index or occurrence
of an element in a tuple. This function basically performs two functions:
Sorted () :
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.
Ex :
>>>tup = (1,9,6,7,4,5,3)
>>> sorted(tup)
O/P : (1,3,4,5,6,7,9)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Min() :
gives the smallest element in the tuple as an output. Hence, the
name is min().
Ex :
>>>tup = (1,9,6,7,4,5,3)
>>> min(tup)
O/P: 1
max():
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Set :
Unordered collection of various items enclosed within the curly braces.
The elements of the set cannot be duplicate.
The elements of the python set must be immutable.
Example :
Student_id = {10,20,30,40,50}
Print(Student_id)
Output :
{10,20,30,40,50}
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items
after the set has been created.
Once a set is created, you cannot change its items, but you can remove
items and add new items.
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Example 1:
for x in set:
print(x)
Example 2 :
print("banana" in set)
Change Items :
Once a set is created, you cannot change its items, but you can add
new items
Adding Elements :
Once a set is created, you cannot change its items, but you can add new
items.
set1.add("orange")
print(set1)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Update Sets
To add items from another set into the current set, use
the update() method.
set1.update(set2)
print(set1)
numbers = {2, 3, 4, 5}
# removes 3 and returns the remaining set
numbers.discard(3)
print(numbers)
# Output: numbers = {2, 4, 5}
Remove() :
The remove() method removes the specified element from the set.
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Pop() :
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.
Ex :
A = {'a', 'b', 'c', 'd'}
removed_item = A.pop()
print(removed_item)
# Output: c
del keyword :
the del will delete the set completely:
set = {"apple", "banana", "cherry"}
del set
print(set)
union(s) Method:
It returns a union of two set.Using the operator ‘|’between 2
existing sets is the same as writing My_Set1.union(My_Set2).
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
intersect(s) Method:
It returns an intersection of two given sets. The ‘&’ operator can be
used in this operation.
Return a set that contains the items that exist in both set x, and
set y
Example :
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
W = A.difference(B)
OR
S=A–B
Output : Set safe will have all the elements that are in A but not
in B.
W = { "BB", "CC"}
output : True
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Ex 2 :
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b"}
z = x.issubset(y)
print(z)
Output : False
Method Description
All() Return True if all elements of the set are true (or if
the set is empty).
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Dictionary :
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to
by using the key name.
It is the mutable data-structure.
The elements Keys and values is employed to create the dictionary.
Keys must consist of just one element.
Value can be any type such as list, tuple, integer, etc.
Example 1:
dict = {
"Name": "Shiv",
“Class": "First",
"Year": 2018,
"school": “Sinhgad”
}
print(dict)
Example 2 :
dict = {
"brand": "Ford",
"electric": False,
"year": 1964,
colors": ["red", "white", "blue"]}
Print(dict)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Example :
The keys() method will return a list of all the keys in the dictionary.
dict = {
"Name": "Shiv",
“Class": "First",
"Year": 2018,
"school": “Sinhgad”
}
X=dict.keys() # getting keys
Y=dict.values() # getting Values
You can change the value of a specific item by referring to its key
name:
Example :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from
the given argument.
Example :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Example :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
1. Pop()
The pop() method removes the item with the specified key
name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
2. Del :
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang", "year": 1964 }
1. Clear() :
The clear() method empties the dictionary: thisdict = {
"brand": "Ford",
"model": "Mustang", "year": 1964
}
thisdict.clear() print(thisdict)
Mrs.KAJAL. G. RAUT
Programming With Python (22616)
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the
key, with the specified value
Mrs.KAJAL. G. RAUT