UNIT II
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", "m
ango"]
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])
["apple", "banana", "cherry"]
Updating List Values :
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)
Output: [1, 2, 10, 4, 5, 6]
List[1:3] = [28, 69]
print(List)
Output : [1, 28, 69, 4, 5, 6]
Example 2 :
Change the second and third value by replacing it with one value:
list = ["apple", "banana", "cherry"]
list[1:3] = ["watermelon"]
print(list)
Deleting List values :
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]
The del keyword also removes the specified
index: List = [0,1,2,3,4]
print(List)
Output: [0, 1, 2, 3, 4]
del List[0]
print(List)
Output : [ 1, 2 , 3 , 4 ]
The remove() method removes the specified item.
list = ["apple", "banana", "cherry"]
list.remove("banana")
print(list)
Output: ['apple', 'cherry']
The clear() method empties the list, The list still remains, but it has
no content.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Output: [
Basic List Oparations :
1. Indexing
2. Slicing
Operator Description Example
Repetition The repetition operator enables the list elementsL1= [1,2,3,4]
to be repeated multiple times. L1*2 = [1, 2, 3,4, 1, 2,
3, 4]
Concatenation It concatenates the list mentioned on either sideL1= [1,2,3,4]
of the operator. L2=[5,6,7]
L1+L2 = [1, 2, 3, 4, 5,
6, 7, 8]
Membership It returns true if a particular item exists in a L1= [1,2,3,4]
particular list otherwise false. print(2 in L1)
True
Iteration The for loop is used to iterate over the list for i in l1:
elements print(i)
Length It is used to get the length of the list len(l1) = 4
Python List Built-in functions :
Functions Description
cmp(list1, list2) It compares the elements of both the lists.
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.
A tuple can be defined as follows :
T1 = (01, "Shiv", 2018)
T2 = ("Apple", "Banana", "Orange")
Accessing Tuple :
The indexing in the tuple starts from 0 and goes to length(tuple) -
1.
The items in the tuple can be accessed by using the slice
operator. Python also allows us to use the colon operator to
access multiple items in the tuple.
Tuple = (1,2,3,4,5,6)
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)
Deleting values in Tuple :
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.
Built in tuple Funtions :
len() Function :
This function returns the number of elements present in a tuple.
Moreover, it is necessary to provide a tuple to the len() function.
Ex :
>>> tup = (22,11,33,44,55)
>>>
len(tup) O/P
:5
Count() :
This function will help us to fund the number of times an element
is present in the tuple. Furthermore, we have to mention the element
whose count we need to find, inside the count function.
Ex :
>>>tup = (22,11,33,22,44,22,22,55)
>>> tup.count(22)
O/P : 4
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:
Giving the first occurrence of an element in the tuple.
Raising an exception if the element mentioned is not found in the
tuple. Ex :
>>>tup = (11,22,33,44,55,66)
>>>
print(tup.index(33)) O/P
:2
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)
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():
gives the largest element in the tuple as an output. Hence, the
name is max().
Ex :
>>>tup = (1,9,6,7,4,5,3)
>>> max(tup)
O/P : 9
Sum() :
gives the sum of the elements present in the tuple as an O/P
:output.
Ex :
>>>tup = (1,9,6,7,4,5,3)
>>>
sum(tup)
O/P : 45
Basic Tuple Operations :
Operator Description Example
Repetition The repetition operator enables the list t = (1, 2, 3, 4, 5)
elements to be repeated multiple times. T1*2 = (1, 2, 3, 4, 5, 1,
2, 3, 4, 5)
Concatenation It concatenates the list mentioned on t1 = (1, 2, 3, 4, 5)
either side of the operator. t2 = (6, 7, 8, 9)
T1+T2 = (1, 2, 3, 4, 5,
6, 7, 8, 9)
Membership It returns true if a particular item exists t = (1, 2, 3, 4, 5)
in a particular list otherwise false. print (2 in T1) prints
True.
Iteration The for loop is used to iterate over the list for i in T1:
elements print(i)
Set :
Unordered collection of various items enclosed within the curly braces.
The elements of the set can not 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(immutable)
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.
Duplicates Not Allowed
Sets cannot have two items with the same
value. Ex:
Set1 = {"apple", "banana", "cherry", "apple"}
print(set1)
Output : {"apple", "banana", "cherry"}
Accessing Elements in Set :
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if
a specified value is present in a set, by using the in keyword.
Example 1:
Set1 = {"apple", "banana", "cherry"} for
x in set:
print(x)
Example 2 :
set = {"apple", "banana", "cherry"}
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.
To add one item to a set use the add() method.
set1 = {"apple", "banana", "cherry"}
set1.add("orange")
print(set1)
Output: {"orange","apple", "banana", "cherry"}
Update Sets
To add items from another set into the current set, use
the update() method.
set1 = {"apple", "banana", "cherry"}
set2 = {"pineapple", "mango", "papaya"}
set1.update(set2)
print(set1)
Output : {"apple", "banana", "cherry","pineapple", "mango", "papaya"}
Removing Items from the set :
Following methods used to remove the items from the set
1. discard
2. remove
3. pop
discard() : method Python provides discard() method which can
be used to remove the items from the set.
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.
This method is different from the discard() method, because
the remove() method will raise an error if the specified item does
not exist, and the discard() method will not.
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
output: {"apple”, "cherry"}
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.
The return value of the pop() method is the removed item.
Ex :
A = {'a', 'b', 'c', 'd'}
removed_item = A.pop()
print(removed_item)
# Output: c
Ex 2 : Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
del keyword :
the del will delete the set completely:
set = {"apple", "banana", "cherry"}
del set
print(set)
Basic Set Operations :
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).
A = {"AA", "BB", "CC"}
B = {"MM", "NN"}
Z = A.union(B)
OR
Z = A|B
Output : {"AA", "BB", "CC","MM", "NN"}
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)
difference(s) Method: Returns a set containing all the elements
which are existing in the first set but not present in the second
set. We can use ‘-‘ operator here.
A = {"AA", "BB", "CC"}
B = {"MM", "NN","AA"}
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"}
issubset() : The issubset() method returns True if all items in
the set exists in the specified set, otherwise it returns False.
Ex 1 :
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
output : True
Ex 2 :
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b"}
z = x.issubset(y)
print(z)
Output : False
Built-in Set Functions :
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
All() Return True if all elements of the set are true (or if
the set is empty).
any() Return True if any element of the set is true. If
the set is empty, return False.
discard() Remove the specified item
Enumerate() Return an enumerate object. It contains the index
and value of all the items of set as a pair.
pop() Removes an element from the set
remove() Removes the specified element
update() Update the set with another set, or any
other iterable
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)
Accessing values in Dictionary :
You can access the items of a dictionary by referring to its key
name, inside square brackets:
Example :
dict = { "Name": "Shiv", “Class": "First", "Year": 2018, "school":
“Sinhgad”
}
X=dict[Class]
Get Keys and Values
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
Updating Values in /dictionary :
You can change the value of a specific item by referring to its key
name:
Example :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from
the given argument.
The argument must be a dictionary, or an iterable object with
key:value pairs.
Example :
thisdict =
{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key
and assigning a value to it:
Example :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Deleting values in Dictionary :
There are several methods to remove items from a dictionary:
1. Pop()
name: The pop() method removes the item with the specified key
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
}
del thisdict
print(thisdict)
3. Clear() :
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Built-in Dictionary Operations :
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert
the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
========================================================