Unit Iii - Data Structures in Python
Unit Iii - Data Structures in Python
Defining List:
All the items in the list should be put in square brackets
[ ]and separated by commas.
Syntax for defining list:
list_name=[value1,value2,....value n]
Here, list name is the name of list and value1...value n are the
values assigned to list.
CREATING A LIST
# empty list
my_list = [ ]
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This
is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
ACCESSING VALUES IN LIST
To access values in lists, use the square brackets for slicing
along with the index or indices to obtain value available at
that index.
Example:
List1=[‘physics’, ‘chemistry’, 1997, 2000]
List2=[1,2,3,4,5]
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
Negative indexing
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
DELETING VALUES IN LIST:
There are many ways to delete elements from list.
1. pop()method,
2. del keyword,
3. remove() method
4. clear() method
We can use remove() method to remove a particular element
from the list.
pop() method to remove an item at the given index. The pop()
method removes and returns the last item if index is not
provided. This helps us implement lists as stacks (first in, last
out data structure).
We can also use the clear() method to empty a list.
We can delete one or more items from list using del keyword. It
can even delete the list entirely.
EXAMPLE: DELETING VALUES IN LIST
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)
my_list.remove('p')
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)
print(my_list.pop(1))
# Output: ‘o'
print(my_list)
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list.pop())
# Output: 'm'
print(my_list)
# Output: ['r', 'b', 'l', 'e']
my_list.clear()
# Output: [ ]
UPDATE OR ADD ELEMENTS TO A LIST:
List are mutable, meaning, their elements can be changed unlike
string or tuple.
We can use assignment operator (=) to change an item or a
range of items.
# mistake values
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] =1
# Output: [1, 4, 6, 8]
print(odd)
odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3, 9]
print(odd)
odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
UPDATE OR ADD ELEMENTS TO A LIST:
We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
thislist = [5,2,11,4]
thislist.sort()
print(thislist)
OUTPUT: [2,4,5,11]
thislist = [5,2,11,4]
thislist.sort(reverse=True)
print(thislist)
OUTPUT: [11, 5, 4, 2]
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
>>>list1[3:]
[40,50]
>>>list1[-1]
50
BASIC LIST OPERATIONS -INDEXING,
SLICING
Slicing:
Itis an operation to extract elements from the list, it is used to
form subset.
Syntax:
List_var[start_index:end_index]
Example:
>>>list1[1:4]
[20,30,40]
BUILT-IN LIST FUNCTIONS AND METHODS-
LIST METHODS
append():Adds an element at the end of the list
index():Returns the index of the first element with the specified value
Here is an example:
a = [1, 2]
b = [6, 7, 8]
a.append(3)
a.append(b)
print(a)
# this will return:
# [1, 2, 3, [6, 7, 8]]
Here is an example:
a = [1, 2]
b = [6, 7, 8]
a.extend(b)
print(a)
# this will return:
# [1, 2, 6, 7, 8]
LIST METHODS WITH EXAMPLE
3. list.clear(): clear() will remove all items from the list in
Python.
Here is an example:
a = [1, 2]
a.clear()
# this will return
#[]
4. list.copy():copy() will create a copy of a list in Python.
Here is an example:
a = [1, 2]
b = a.copy()
print(b)
# this will return
# [1, 2]
LIST METHODS WITH EXAMPLE
5. list.count(): count() will count the number of times a value
appears in a list.
Here is an example:
MyList= [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
countme = MyList.count(‘l’)
print(countme)
# this will return
#3
6. list.index(): index() will find the index position of a value in a
list. Lists start their index at 0. It is also good to note that it will
stop at the first instance of the matched value. For example:
message = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
indexme = message.index(‘l’)
print(indexme)
# this will return
#2
LIST METHODS WITH EXAMPLE
7. list.remove()
We can remove a specific item from the list by using remove().
Note that, similar to index(), it will only remove the first instance
of the matched value. To remove all matched values, we will need
to put them through a loop. For example:
letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]
letters.remove(‘f’)
print(letters)
# this will return
# [‘a’, ‘b’, ‘c’, ‘f’]
Here’s an example of a loop to remove all values inside a list. We
pair this with range() to know how many times it appears.
letters = [‘a’, ‘b’, ‘f’, ‘c’, ‘f’]
for item in range(letters.count(‘f’))
letters.remove(‘f’)
LIST METHODS WITH EXAMPLE
8. list.pop()
pop() will eject the last item from the array. For example:
c=max(list1)
print(c)
print("common elements:",list3)
tuple_name=(value1,valu2....value n)
CREATING TUPLE
For example
Tup1=(‘physics’,’chemistry’,’1997,2000)
Tup2=(1,2,3,4,5)
Python often recognizes that a tuple is intended even if the
parentheses are missing:
Tup3=‘a’, ‘b’, ‘c’, ‘d’
For completeness, 0- and 1-element tuples can be defined,
but have special syntax:
a = ( ) # 0-tuple (empty tuple)
b = (item,) # 1-tuple (note the trailing comma)
c = item, # 1-tuple (note the trailing comma)
e.g tup1=(50,)
ACCESSING VALUES IN TUPLES
To access values in tuple, use the square brackets for slicing
along with the index or indices to obtain value available at that
index.
One can access the elements of a tuple in multiple ways, such
as indexing, negative indexing, range, etc.
For example –
tup1=(12, 34.56)
tup2=(‘abc’,’xyz’)
# following action is not valid for tuples
tup1[0]=100
Example:
tup1=(12, 34.56)
print(tup1)
del tup1
print(“After deleting tup1”)
print(tup1)
Output: Traceback (most recent call last):
File "F:\2019-2020\PYTH prog\tup_ex.py", line 2, in print(tup1)
NameError: name 'tup1' is not
BASIC TUPLES OPERATIONS
Indexing in Tuples: Indexing in tuples is also pretty similar to
that in lists, the first element has index zero, and it keeps on
increasing for the next consecutive elements.
Also, backward indexing is also valid in tuples, i.e., the last
element can be accessed using the index -1 and the consecutive
previous numbers by -2, -3 and so on. Let's take an example,
>>> example = ("apple", "orange", "banana", "berry", "mango" )
>>> print (example[0]);
Output:
‘apple’
BASIC TUPLES OPERATIONS
Slicing Tuple:
As tuples are immutable, we can take slices of one tuple
and place them in another tuple.
>>> t = (1, 2, 3, 4)
>>> print(t[2:4])
(3,4)
Here, t[2:4] means, slice the tuple starting from
index 2 upto the index 4, and take that slice out.
Slicing can be done backwards as well using the negative
indexes for traversing the tuple from backward direction.
BASIC TUPLES OPERATIONS
Concatenation Operation :Concatenation simply
means linking things together. We can concatenate tuples
together.
Here note one thing we can perform different operations
on tuples without changing its own definition.
Tuple1 = (1, 3, 4)
Tuple2 = (‘red’, ’green’, ‘blue’)
print (Tuple1 + Tuple2)
Output:
(1,3,4,’red’,’green’,’blue’)
BASIC TUPLES OPERATIONS
Repetition operation:
We can also repeat the elements in tuple for given number of
times using * operator.
>>>tuple1=(1,2,3)
>>>tuple1*2
Output:
(1,2,3,1,2,3)
BUILT IN TUPLE FUNCTIONS:
Python has some built-in functions which can be performed directly
on the tuples.
For e.g.,
1. max(),
2. min(),
3. len(),
4. sum(),
5. sorted() etc.
max(tuple): It gives the maximum value from the tuple; here, the
tuple should not contain string values.
Code:
tuple1 = (1, 2, 3, 6)
print(max(tuple1))
Output:
6
BUILT IN TUPLE FUNCTIONS:
min(tuple): It gives the minimum value from the tuple; here the
condition is tuple should not contain string values.
Code:
tuple1 = (1, 2, 3, 6)
print(min(tuple1))
Output:
1
len(tuple) – Description The function len() returns the number of elements in the tuple.
Syntax :len(tuple)
tup1,tup2=(123,'XYZ','PQR'),(456,'abc')
print(len(tup1))
print(len(tup2))
Output:
3
2
METHODS OF TUPLE: (NOT IN
SYLLABUS READ ONCE)
Count()- Returns the number of times a specified value
occurs in a tuple.
index()- Searches the tuple for a specified value and
returns the position of where it was found.
Example
tuple1=(123,789,123)
print(tuple1.index(789))
print(tuple1.count(123))
Output
1
2
SETS { }:
A Python set is the collection of the unordered items. Each
element in the set must be unique, immutable, and the sets
remove the duplicate elements. Sets are mutable which means
we can modify it after its creation.
It is an unordered collection of objects, meaning it does not
record element position or order of insertion and so cannot
access elements using indexes.
A set object contains one or more items, not necessarily of the
same type, which are separated by a comma and enclosed in
curly brackets {}.
SETS:
A set doesn't store duplicate objects. Even if an object is
added more than once inside the curly brackets, only one
copy is held in the set object. Hence, indexing and slicing
operations cannot be done on a set object.
Only immutable (and hashable) objects can be a part of a
set object. Numbers (integer, float, as well as complex),
strings, and tuple objects are accepted, but set, list, and
dictionary objects are not.
Syntax:
Set_name={value1,value2,...valuen}
DEFINING AND ACCESSING ELEMENTS
IN SET
A set contains an unordered collections of items. Set is
defined by values separated by comma inside braces {}.
Another method is by making use of set()
set1=set(['p','q','r','s'])
for i in set1:
print(i)
Output
p
r
q
s
DELETING VALUES IN SET–
There are different ways to delete values in a set.
Elements/items in set can be deleted using pop, remove or
discard method as shown in example.
pop method removes random item from a set and return it.
Example–
set1={'p','q','r','s'}
set1.add('E')
print(set1)
Output-
Loops can be used to add multiple elements at a time using add() method.
Example-
set1={'p','q','r','s'}
t={1,2}
for i in t:
set1.add(i)
print(set1)
Output:
Example-
set1={'p','q','r','s'}
set1.add('E')
print(set1)
set1.update({'G','A'})
print(set1)
output-
{'r', 'E', 'p', 's', 'q'}
{'r', 'E', 'A', 'G', 'p', 's', 'q'}
BASIC SET OPERATIONS
Set has four basic operations which are enlisted below
1) Union,
2) Intersection,
3) Difference and
4) Symmetric Difference
Union- Union operation performed on two sets returns all the elements
from both the sets.
Union of set A and set B is defined as the set that consists of all
elements belonging to either set A or set B(or both).
It is performed by using | operator.
Example:
A={1,2,4,6,8} OR A=set([1,2,4,6,8])
B={1,2,3,4,5} B=set([1,2,3,4,5])
C=A|B C=A|B
print(C) print(C)
Output- {1, 2, 3, 4, 5, 6, 8}
SET UNION
BASIC SET OPERATIONS
Intersection-
Intersection operation performed on two sets returns all the elements
which are common or in both the sets.
Intersection of set A and set B is defined as the set that consists of
all elements that belong to both A and B.
It is performed by using & operator.
Example–
A={1,2,4,6,8}
B={1,2,3,4,5}
C=A&B
print(C)
Output-
{1, 2, 4}
BASIC SET OPERATIONS
Difference-
Difference operation performed on two sets returns all the elements
which are present in set 1 but not in set2.
It is performed by using - operator.
Example–
A={1,2,4,6,8}
B={1,2,3,4,5}
C=A-B
print(C)
Output-
{8, 6}
BASIC SET OPERATIONS
Symmetric Difference-
Symmetric difference operation is performed by using
^(XOR) operator.
The Symmetric difference of two sets returns all the elements
which belongs either to set 1 or set2 but not both.
It is performed by using ^ operator.
A={1,2,4,6,8}
B={1,2,3,4,5}
C=A^B
print(C)
Output-
{3, 5, 6, 8}
# PROGRAM TO PERFORM DIFFERENT SET OPERATIONS
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
# symmetric difference
print("Symmetric difference :", A ^ B)
Output-
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))
BUILT-IN SET METHODS
add() – Adds an element to a set
clear()- Removes all elements from the set
e.g.
A={1,2,4,6,8}
B={2,4}
print(A)
A.clear()
print(A)
B.add(5)
print(B)
Output-
{1, 2, 4, 6, 8}
set()
{2,5,4}
BUILT-IN SET METHODS
union() – Returns a new set containing the union of two or
more sets.
intersection()- Returns a new set which is the intersection of
two or more sets
e.g.
A={1,2,4,6,8}
B={2,4}
print(A.union(B))
print(A.intersection(B))
Output-
{1, 2, 4, 6, 8}
{2, 4}
BUILT-IN SET METHODS
difference() – Returns a new set containing the difference
between two or more set.
e.g. A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
print(A.difference(B))
Output :
{0, 8, 6}
symmetric_difference()- Returns a new set with the
symmetric differences of two or more sets.
e.g. A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
print(A.symmetric_difference(B))
Output-
{0, 1, 3, 5, 6, 8}
BUILT-IN SET METHODS
isdisjoint() – Return true if two sets have null intersection.
e.g. A={1,2,4,6,8}
B={3,5}
print(A.isdisjoint(B))
Output
True
issubset()- Report whether another set contains this set.
e.g. A={1,2,4,6,8}
B={2,6}
print(B.issubset(A))
Output
True
BUILT-IN SET METHODS
issuperset() – Determines whether one set is a superset of the
other.
e.g. A={1,2,4,6,8}
B={1,2,4}
print(A.issuperset(B))
Output
True
pop()- Remove and return an arbitrary set element. Raises
keyerror if the set is empty.
e.g. A={5,2,4,6,8}
print(A)
print(A.pop())
Output-
{2, 4, 5, 6, 8}
2
BUILT-IN SET METHODS
remove() – Remove an element from a set, which must be a
member.
If the element is not a member, raise a keyerror.
e.g. A={5,2,4,6,8}
print(A)
A.remove(4)
print(A)
Output-
{2, 4, 5, 6, 8}
{2, 5, 6, 8}
BUILT-IN SET FUNCTIONS
all() – Return True if all elements of the set are True(or if the set is empty)
e.g.
set1={'p','q','r','s'}
print(all(set1))
set2=set()
print(all(set2))
set3={0,1,2,3}
print(all(set3))
Output
True
True
False
set1={'p','q','r','s'}
any() – Return True if any elements of the set is True. If the set is empty, return False.
print(any(set1))
e.g. set1={'p','q','r','s'} OR set2={0,1}
print(any(set1)) print(any(set2))
set2=set() set3={0}
print(any(set2)) print(any(set3))
Output OUTPUT-
True
True
True
False
BUILT-IN SET FUNCTIONS
len() – Return the length (number of items) in the set. e.g.
set1={'p','q','r','s'}
print(len(set1))
set2=set()
print(len(set2))
Output
4
0
max() – Return the largest item in the set. e.g. set1={'p','ss','st','sz','r','q'}
print(max(set1))
set2={4,5,1,2}
print(max(set2))
Output
sz
5
BUILT-IN SET FUNCTIONS
min() – Return the smallest item in the set. e.g.
set1={‘r','q',‘p','s'}
print(min(set1))
set2={4,5,1,2}
print(min(set2))
Output
p
1
sorted() – Return a new sorted list from elements in the set. e.g. set1={4,5,1,2}
print(set1)
Output-
[1, 2, 4, 5]
{'a', 'k', 'm', 'mzt', 'f', 'mm'}
BUILT-IN SET FUNCTIONS
sum() – Return the sum of all elements in the set. e.g.
set1={4,5,1,2}
print(sum(set1))
Output
12
#WRITE A PYTHON PROGRAM TO CREATE A SET, ADD
MEMBER(S) IN A SET AND REMOVE ONE ITEM FROM A SET
s1={5,8,10,5,7} Output-
print(s1) {8, 10, 5, 7}
s1.add(3) {3, 5, 7, 8, 10}
print(s1) {3, (2, 6), 5, 7, 8, 10}
s1.add((2,6)) {3, (2, 6), 5, 7, 8}
print(s1) {(2, 6), 5, 7, 8}
s1.remove(10)
print(s1)
s1.pop()
print(s1)
DICTIONARIES :
Dictionary data structure is used to store key value pairs
indexed by keys.
Dictionary in Python is an unordered collection of data values,
used to store data values like a map, which unlike other Data
Types that hold only single value as an element.
It has a key: value pair where each value is associated with a
key.
A key and its value are separated by a colon(:) between them.
The popitem() method removes the item that was last inserted
into the dictionary.
o/p
Initial Dictionary: {5: 'A', 6: 'To', 7: 'Z', 'A': {1: 'Amol',
2: 'Ramesh', 3: 'Arun'}, 'B': {1: 'Amit', 2: 'Rahul'}}
# DELETING A KEY VALUE
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
o/p
Deleting a specific key: {5: 'A', 7: 'Z', 'A': {1: 'Amol', 2: 'Ramesh', 3:
'Arun'}, 'B': {1: 'Amit', 2: 'Rahul'}}
o/p
Popping specific element: {7: 'Z', 'A': {1: 'Amol', 3: 'Arun'}, 'B': {1:
'Amit', 2: 'Rahul'}}
# DELETING A KEY FROM NESTED DICTIONARY
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)
o/p
Deleting a key from Nested Dictionary: {5: ‘A', 7: 'Z', 'A': {1: 'Amol',
3: 'Arun'}, 'B': {1: 'Amit', 2: 'Rahul'}}
print(dict1)
Example
dict1={'name':'vijay','age':40}
dict1['add']='Kolhapur'
print(dict1)
print(dict1)
print(1 in dict1)
print(6 in dict1)
o/p- {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
True
False
BASIC DICTIONARY OPERATIONS
Traversing Dictionary:
Using a for loop we can iterate through each key in a
dictionary.
Example dict1={1:1,2:4,3:9,4:16,5:25}
for i in dict1:
print(i,dict1[i])
o/p
1 1 2 4 3 9 4 16 5 25
BUILT-IN DICTIONARY FUNCTIONS :
Built-in functions like all(), any(), len(), cmp(), sorted() etc. are
commonly used with dictionary to perform different tasks.
all() - Return True if all keys of the dictionary are true (or if the
dictionary is empty).
any() - Return True if any key of the dictionary is true. If the
dictionary is empty, return False.
len() - Return the length (the number of items) in the
dictionary.
sorted() -Return a new sorted list of keys in the dictionary
EXAMPLE
squares = {1: 1, 7: 9, 5: 25, 3: 49, 9: 81}
squares1={}
print(all(squares))
print(any(squares1))
print(len(squares))
print(sorted(squares))
Output
True
False
5
[1, 3, 5, 7, 9]
BUILT-IN DICTIONARY METHODS
clear() - Removes all the elements from the dictionary.
copy() – Returns a copy of the dictionary
fromkeys() – It creates a new dictionary with default value for all
specified keys. If the default value is not specified all the keys are set
to none.
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 keys.
pop() – Removes the element with the specified key.
popitem() – The popitem() method removes the item that was last
inserted into the dictionary.
setdefault() - It is similar to get(), but will set dict[key]=default if key
is not already in dict.
update() – Updates the dictionary with key-value pairs of another
dictionary.
EXAMPLE-# BUILT-IN DICTIONARY METHODS
squares = {1:1, 2:4, 3:9, print(squares.get(2))
4:16, 5:25} for i in squares.items():
squares3={} print(i)
print(squares.pop(4)) print(squares.keys())
print(squares) squares1.setdefault(7,None)
squares1=squares.copy() print(squares1)
print(squares1) squares3.update(squares)
print(squares.popitem()) print(squares3)
print(squares) print(squares.values())
squares2=squares.fromkeys squares.clear()
([1,3],5)
print(squares)
print(squares2)
OUTPUT
16
{1: 1, 2: 4, 3: 9, 5: 25}
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{1: 5, 3: 5}
4
(1, 1)
(2, 4)
(3, 9)
dict_keys([1, 2, 3])
{1: 1, 2: 4, 3: 9, 5: 25, 7: None}
{1: 1, 2: 4, 3: 9}
dict_values([1, 4, 9])