Chapter 3
Chapter 3
Chapter 3
CHAPTER 3
DATA STRUCTURES IN PYTHON
Data Structures in
Python
List Accessing values, Basic List Operations Built-in List Functions
deleting values,
updating lists
Tuple Accessing values, Basic Tuple Built-in Tuple
deleting values, Operations Functions
updating Tuple
Set Accessing values, Basic Set Operations Built-in Set Functions
deleting values,
updating Set
Dictionary Accessing values, Basic Dictionary Built-in Dictionaries
deleting values, Operations Functions
updating Dictionary
LISTS:-DEFINING LISTS
List is a sequence of values written in a square bracket and
separated by commas.
Syntax
<list_name>= [value1,value2,……valueN]
Where
List_name=name of the list
value1,value2,……valueN are list of values assigned to the list
For example:-
Create list:-
>>>rollno=[1,2,3,4,5]
>>> name=["swati","yash","chinmaya","shilpa"]
CREATE A LIST USING INBUILT FUNCTION RANGE()
>>> A=list(range(0,5))
>>> A
[0, 1, 2, 3, 4]
ACCESSING VALUES IN LIST
Individual element of the list can be accessed using index of the list.
>>> A=["one",20,2.3,"five"]
>>> A[2]
2.3
>>> A[-2]
2.3
>>> A[1:3]
[20, 2.3]
>>> A[3:]
['five']
>>> A[2:]
[2.3, 'five']
>>> A[:4]
['one', 20, 2.3, 'five']
>>> A[:3]
['one', 20, 2.3]
>>>
ITERATING THROUGH LIST USING FOR LOOP
l=[2,2.3,"hello",89]
for ele in l:
print(ele)
O/P:--
2
2.3
hello
89
>>>
PYTHON PROGRAM TO PERFORM SUM OF ELEMENTS OF A LIST
l1=[1,2,1,1,1]
sum=0
for ele in l1:
sum=sum+ele
print("sum=",sum)
O/P:--
sum= 6
>>>
PYTHON PROGRAM TO CALCULATE SQUARE AND CUBE OF LIST ELEMENTS.
l1=[1,2,3,4,5]
for ele in l1:
sq=ele*ele
cu=ele*ele*ele
print(ele,"=>",sq,"=>",cu)
O/P:-
1 => 1 => 1
2 => 4 => 8
3 => 9 => 27
4 => 16 => 64
5 => 25 => 125
>>>
SLICING OPERATOR(:)ON LIST
To print a specific range of elements of a list, we use slice operation.
The Slice operation is performed on List with the use of colon(:).
Following varieties to perform slicing operation:--
Syntax:-
list_name.insert(index , element)
EXTEND()
Syntax:-
list1.extend(list2)
PROGRAM:-
list1=[10,20,30]
list2=[13,12,45,20]
list1.extend(list2)
print(list1)
print(list2)
O/P:-
[10, 20, 30, 13, 12, 45, 20]
[13, 12, 45, 20]
DELETING VALUES IN LIST
The deletion of any element from the list is carried out by using various function like pop(),
remove(), del()
>>> l=["p","y","t","h","o","n"]
>>> l
['p', 'y', 't', 'h', 'o', 'n']
>>> del l[2]
>>> l
['p', 'y', 'h', 'o', 'n']
>>> del l[1:3]
>>> l
['p', 'o', 'n']
>>> del l
>>> l
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
l
NameError: name 'l' is not defined
>>>
BUILT-IN LIST FUNCTIONS
Sr.No. Built-in Function Description
1 Len(list) It returns the length of the
list
2 Max(list) It returns the maximum
element present in the list.
3 Min(list) It returns the minimum
element present in the list
4 Sum(list) It returns the sum of all
elements in the list
5 List.sort() It returns a list which is
sorted one.
PYTHON PROGRAM USING BUILT-IN FUNCTION
>>> b=[1,2,3,4,5,30]
>>> max(b)
30
>>> min(b)
1
>>> sum(b)
45
>>> len(b)
6
>>> b.count(2) # It returns the number of times the item occurs in the
list.
1
PYTHON PROGRAM TO CREATE A LIST OF EVEN NUMBERS
FROM 0 TO 10.
even=[]
for i in range(11):
if i%2==0:
even.append(i)
print("even number list=",even)
O/P:-
even number list= [0, 2, 4, 6, 8, 10]
>>>
PYTHON PROGRAM TO TO ACCEPT N NUMBERS FROM USER. COMPUTE AND DISPLAY
MAXIMUM IN LIST, MINIMUM IN LIST, SUM AND AVERAGE OF NUMBERS.
list=[]
print("Enter the value of N:")
N=int(input())
for i in range(N):
print("enter the element")
element=int(input())
list.append(element)
a=10
b=20
print(a,b)
a,b=b,a
print(a,b)
ACCESSING VALUES IN TUPLE
>>> tuple=(10,20,30)
>>> tuple[1]
20
>>> tuple(1)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
tuple(1)
TypeError: 'tuple' object is not callable
>>> tuple[2:]
(30,)
>>> tuple[:2]
(10, 20)
DELETING TUPLES
Tuples are immutable, so we cannot remove elements from it, but we can delete the tuple
completely.
Delete a entire tuple—use del statement
>>> A=(12,2.3,"python")
>>> A
(12, 2.3, 'python')
>>> del A
>>> A
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
A
NameError: name 'A' is not defined
>>>
UPDATING TUPLE
Tuples are immutable that means values in the tuple can not be
changed. We can only extract the values of one tuple to create
another tuple.
>>> T1=(10,20,30)
>>> T2=(40,50)
>>> T3=T1+T2
>>> print(T3)
(10, 20, 30, 40, 50)
>>>
CONVERSION FROM TUPLE INTO A LIST
Python list method list() takes sequence types and converts them to
lists. This is used to convert a given tuple into list.
Note − Tuple are very similar to lists with only difference that
element values of a tuple can not be changed and tuple elements are
put between parentheses instead of square bracket.
Syntax
list( seq )
Parameters
seq − This is a tuple to be converted into list.
Return Value
This method returns the list.
CONVERSION FROM TUPLE INTO A LIST
>>> B=(1,2,3,4,5,6,7)
>>> B.pop()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
B.pop()
AttributeError: 'tuple' object has no attribute 'pop'
>>> A=list(B)
>>> A
[1, 2, 3, 4, 5, 6, 7]
>>> A.pop()
7
>>> A
[1, 2, 3, 4, 5, 6]
>>> A.append(30)
>>> A
[1, 2, 3, 4, 5, 6, 30]
>>>
TUPLE ASSIGNMENT
Python tuples are immutable means that they can not be modified in
whole program. Packing and Unpacking a Tuple : In Python there is
a very powerful tuple assignment feature that assigns right hand side
of values into left hand side.
SET IN PYTHON
SET
set={"apple",20,"hello"}
>>> set
{'hello', 'apple', 20}
ACCESS ITEMS IN SET
You cannot access items in a set by referring to an index, since sets are
unordered the items has no index.
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.
>>> set{1}
SyntaxError: invalid syntax
>>> for x in set:
print(x)
hello
apple
20
Check if “apple" is present in the set:
>>> print("apple" in set)
True
>>> print(23 in set)
False
CHANGE ITEMS IN SET
Once a set is created, you cannot change its items, but you can add new items.
Add Items
o To add one item to a set use the add() method.
o To add more than one item to a set use the update() method.
set={"apple",20,"hello"}
>>> set.add(3.4)
>>> set
{3.4, 'hello', 'apple', 20}
Add multiple items to a set, using the update() method:
>>> B.update([2.5,"hello",34])
>>> B
{2.5, 34, 5, 6, 'hello', 'welcome to python'}
Remove(): to remove the item from the set
TO FIND THE LENGTH OF SET
The union of two or more sets is the set of all distinct elements
present in all the sets.
A={1,2,2.4,"hello"}
>>> B={5,6,"hi"}
>>> A.union(B)
{1, 2, 2.4, 5, 6, 'hi', 'hello'}
INTERSECTION OF 2 SETS
Values in a dictionary can be of any datatype and can be duplicated, whereas keys
can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, same name but different cases of Key
will be treated distinctly.
THE END