Chapter 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

Data Structure in Python

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:--

o To print elements from beginning to a range, use syntax[:index]


o To print elements from end,use syntax[: -index]
o To print elements from specific index till the end, use syntax[index:]
o To print elements within a range, use syntax[Start_index:End_index]
o To print whole list with the use of slicing operation, use syntax [:]
o To print whole list in reverse order, use syntax[::-1]
ADDING ELEMENT
After creating a list, we can use 3 functions append(),insert() and
extend() functions to add new elements in it.
1) append()

It adds specified element to the last position of list.


Syntax:-
list_name.append(new_element)
list=[]
USE APPEND() TO ACCEPT AND ADD ELEMENTS FROM THE USER.
print("enter 5 elements for list")
i=1
while(i<=5):
val=input()
list.append(val)
i=i+1
print("list contains=",list)
O/P:-
enter 5 elements for list
1
hello
2.3
3
4
list contains= ['1', 'hello', '2.3', '3', '4']
INSERT()

This function inserts an element at specified position.

Syntax:-
list_name.insert(index , element)
EXTEND()

This function extend elements of list2 with list1.

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()

Pop()– this function removes element from specified index.


Syntax:--
lis_name.pop(index_number)
>>> a=["u","v",2,"w"]
>>> val=a.pop()
>>> a
['u', 'v', 2]
>>> val=a.pop(1)
>>> a
['u', 2]
>>>
REMOVE() & DEL()

This function removes specified element from a list.


Syntax:-
list_name.remove(element)
>>> a=["u","v",2,"w"]
>>> val=a.pop()
>>> a
['u', 'v', 2]
>>> val=a.pop(1)
>>> a
['u', 2]
>>> a.pop()
2
>>> a.append(30)
>>> a
['u', 30]
>>> a.extend([35,45,89])
>>> a
['u', 30, 35, 45, 89]
>>> a.pop()
89
>>> a
['u', 30, 35, 45]
>>> a.remove()
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a.remove()
TypeError: remove() takes exactly one argument (0 given)
>>> a.remove(30)
>>> a
['u', 35, 45]
>>> a.remove(15)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
a.remove(15)
ValueError: list.remove(x): x not in list
>>>
DEL()
Del()—this function removes one or more element from the list and even it can remove entire list

>>> 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)

print("the list is:")


print(list)

print("The maximum element from the list is:")


max_element=list[0]
for i in range(N):
if(list[i]>max_element):
max_element=list[i]
print("The minmum element from the list is:")
min_element=list[0]
for i in range(N):
if(list[i]<min_element):
min_element=list[i]
print("min_element",min_element)

print("the sum of all numbers in the list is:")


sum=0
avg=0.0
for i in range(N):
sum=sum+list[i]
print(sum)
avg=sum/N
print("the average =",avg)
O/P:-
Enter the value of N:
4
enter the element
2
enter the element
40
enter the element
20
enter the element
20
the list is:
[2, 40, 20, 20]
The maximum element from the list is:
max_element 40
The minmum element from the list is:
min_element 2
the sum of all numbers in the list is:
82
the average = 20.5
TUPLE
Tuple is a collection of element which are enclosed within parenthesis and these
elements are separated by commas.
Syntax:-
<tuple_name>=(value1,value2,……valueN)
Python program to swap the value of 2 variables
a=10
b=20
print(a,b)
temp=a
a=b
b=temp
print(a,b)
PYTHON PROGRAM TO SWAP THE VALUE OF 2 VARIABLES USING TUPLE ASSIGNMENT

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

A set is a collection which is unordered and unindexed.


In Python sets are written with curly brackets.

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

Len() is used to find the length of set


>>> l={"welcome",20,2.3}
>>> l
{2.3, 'welcome', 20}
>>> print(len(l))
3
REMOVE() AND DISCARD() METHOD IN SET
>>> l.remove("w")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
l.remove("w")
KeyError: 'w'
>>> l.discard("w")
>>> l.remove("welcome")
>>> l
{2.3, 20}
>>> l.discard(2.3)
>>> l
{20}
JOIN 2 SETS –UNION() METHOD IS USED

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

Returns a set, that is the intersection of two other sets


>>> set={20,"python",3.4}
>>> set1={29,"python",3.2}
>>> set.intersection(set1)
{'python'}
DICTIONARIES
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,
Dictionary holds key : value pair.
Key value is provided in the dictionary to make it more optimized.
PROPERTIES OF DICTIONARY KEYS

There are two important points while using dictionary keys


 More than one entry per key is not allowed ( no duplicate key is
allowed)
 The values in the dictionary can be of any type, while the keys
must be immutable like numbers, tuples, or strings.
 Dictionary keys are case sensitive- Same key name but with the
different cases are treated as different keys in Python dictionaries.
A dictionary is a collection which is unordered, changeable and
indexed.
In Python dictionaries are written with curly brackets, and they
have keys and values.
Syntax:-
<dictionary_name>={key1:value1, key2:value2,…
KeyN:valueN}
Example:-
Emp = {“ID”:20, “Name”:”Amar”, “Salary”:50}
OPERATIONS ON DICTIONARY
 Accessing Values
 Add a value in Dictionary

 Update the value in Dictionary


 Remove the value from the Dictionary
>>> txt="i like python programming very much"
>>> msg=txt.capitalize()
>>> print(msg)
I like python programming very much
>>>
DICTIONARY
 A Dictionary in Python is the unordered and changeable collection of data
values that holds key-value pairs. Each key-value pair in the dictionary maps the
key to its associated value making it more optimized. A Dictionary in python is
declared by enclosing a comma-separated list of key-value pairs using curly
braces({}). Python Dictionary is classified into two elements: Keys and Values.

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

You might also like