0% found this document useful (0 votes)
4 views

unit3

This document provides an overview of data structures in Python, focusing on lists, including their definition, creation, and basic operations such as accessing, deleting, and updating values. It explains various list methods like append, extend, and insert, as well as indexing and slicing techniques. Additionally, it covers built-in functions for lists, highlighting their importance in organizing and manipulating data efficiently.

Uploaded by

divyamundlik21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

unit3

This document provides an overview of data structures in Python, focusing on lists, including their definition, creation, and basic operations such as accessing, deleting, and updating values. It explains various list methods like append, extend, and insert, as well as indexing and slicing techniques. Additionally, it covers built-in functions for lists, highlighting their importance in organizing and manipulating data efficiently.

Uploaded by

divyamundlik21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit 3: Data Structures in Python

C22616.c Perform operations on data structures in Python.


.

Introduction:
A Data Structurer is a specialized format for organizing and storing data
Python has implicit support for Data Structures which enable you to store and access data.
Python has four basic inbuilt data structures namely Lists, Dictionary, Tuple and Set.

Lists:
1.1 Defining lists,accessing values in list
1.2 Deleting values in list, updating Basic List Operations
1.3 Built – in List functions

List
A List in python is linear data structure ie .Lists are used to store data of different data types in a
sequential manner. There are addresses assigned to every element of the list, which is called as
Index. The index value starts from 0 and goes on until the last element called the positive index.
There is also negative indexing which starts from -1 enabling you to access elements from the last
to first. Let us now understand lists better with the help of an example program.

Defining a List
In python list are written in square bracket .A List is created by placing all the items (elements
inside a square bracket [] , separated by commas.
Syntax for Defining a List
<list_name> =[val1,val2,………,valN] here list_name is the name of list and val1.val2,valN are
elements of list.
Unit 3: Data Structures in Python

Example
my_list =[1, 2, 3, 'example', 3.132]
List are mutable or changeable .the values of any element can be inside the list can be changed at
any point
Creating a List:
To create a list, you use the square brackets and add elements into it accordingly.

Example 1:

Creating empty list


>>>l= [] #empty List
>>l

Creating list using constructor

>>>l=list () #empty List


>>l
[]

Creating list with integer elements

>>>i=[1,4,12,17] # list of integer


>>>i
[1, 4, 12, 17]

Creating list with string elements

>>>i=[“mango”,”orange”,”banana”] # list of string


>>>l
[‘mango’,’orange’,’banana’]

Creating list with mixed data

>>> l== [1, 2, 3, 'example', 3.132] #creating list with mixed data

Creating list using in built range () function

>>> l=list(range(0,5))
>>l
[0,1,2,3,4]

Creating list with in built character A,B and C

>>> l=list (“ABC”)


>>l
[‘A’,’B’,’C’]
Unit 3: Data Structures in Python

Accessing Values in Lists


To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index. For example
>>> list1=[“one”,”two”,3,10,”six”,20]
>>>list1[0] #positive indexing
‘one
>>>list1[-2] #negative indexing

‘six’
>>>list1[1:3] #get element from mth index to n-1 index
[‘two’,3]
>>>list1[3:] #get element from mth index to last index
[10,’six’,20]
>>>list1[:4] #get element from zero index to n-1
[‘one’,’two’,3,10]

Deleting values in the list

Python provides many ways to delete elements from list

● Use the del keyword which is built-in into Python but this does not return anything back to
us.del function can return one or more items from the list it can also delete list entirely.

● If you want the element back, you use the pop() function which takes the index value. Pop
method removes and returns the last item if index is not provided.

● To remove an element by its value, you use the remove() function.remove function is used
if we know the item that we want to remove or delete from the list (but not the index)

Example:

my_list = [1, 2, 3, 'example', 3.132, 10, 30]


del my_list[5] #delete element at index 5
print(my_list)
my_list.remove('example') #remove element with value
print(my_list)
a = my_list.pop(1) #pop element from list
print('Popped Element: ', a, ' List remaining: ', my_list)
my_list.clear() #empty the list
print(my_list)
Unit 3: Data Structures in Python

Output:
[1, 2, 3, ‘example’, 3.132, 30]
[1, 2, 3, 3.132, 30]
Popped Element: 2 List remaining: [1, 3, 3.132, 30]
[]

Updating lists (change or add element in the list)


List are mutable meaning their elements can be changed or updated unlike string or tuple.
● Mutability is the ability for certain type data to be changed without entirely recreating it.
● Using mutable data type program can be executed quickly and efficiently.
● Assignment operator(=) is used to change an item or a range of item
● List items can be updated by simply assigning the value at a particular index position .we
can also remove the item from the list using ‘remove’ or ‘pop’ or ‘del’ statement

Example 1:

list = ['physics', 'chemistry', 1997, 2000];


print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

Output
When the above code is executed, it produces the following result −

Value available at index 2 :


1997
New value available at index 2 :
2001

Example 2:

>>>list1=[10,20,30,40,50]
>>>list1
[10,20,30,40,50]
>>>list1[0]=0 #change 0th index element
>>>list1
[0,20,30,40,50]
Unit 3: Data Structures in Python

>>>list1[-1]=90 #change last index element


>>>list1
[0,20,30,40,90]
>>>list1[1]=[5,10] #change first element index as sublist
>>>list1
[[5,10],20,30,40,90]

Following table shows the list methods used for updating list
Method Syntax Argument description Return type

append() list.append(item) Item:- can be Only


numbers,strings,anotherlist,dictionar modifies
y original list it
does not
return any
value

extend() list.extend(list2) extend() takes a list and add it to the Only


end modifies
original list it
does not
return any
value

insert() list.insert(index,element index:- is the position where an It does not


) element needs to be added . return any
value. It only
Element:-is the element to be inserted updates the
in the list. current list.

1.append()

The append() method appends an element to the end of the list. The length of the list increases by
one.

Syntax

list.append(elmnt)

Parameter Values
Unit 3: Data Structures in Python

elmnt:- An element of any type (string, number, object etc.)

Example
Add a list to a list:

a = ["apple", "banana", "cherry"]


b = ["Ford", "BMW", "Volvo"]
a.append(b)

output:

['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]

2.extend().

The extend() method adds the specified list elements (or any iterable) to the end of the current list.

Syntax
list.extend(iterable)

Parameter Values

Iterable :- Any iterable (list, set, tuple, etc.)

Example

Add a tuple to the fruits list:

fruits = ['apple', 'banana', 'cherry']


points = (1, 4, 5, 9)
fruits.extend(points)

output:

['apple', 'banana', 'cherry', 1, 4, 5, 9]

3.insert()

The list insert() method inserts an element to the list at the specified index.

syntax

list.insert(i, elem)
Unit 3: Data Structures in Python

Here, elem is inserted to the list at the ith index.


All the elements after elem are shifted to the right.

Parameters

The insert() method takes two parameters:

index - the index where the element needs to be inserted


element - this is the element to be inserted in the list

If index is 0, the element is inserted at the beginning of the list.


If index is 3, the element is inserted after the 3rd element. Its position will be 4th.

Example 1: Inserting an Element to the List

# vowel list
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3
# the position of 'o' will be 4th
vowel.insert(3, 'o')

print('Updated List:', vowel)

Output

Updated List: ['a', 'e', 'i', 'o', 'u']

Example 2: Inserting a Tuple (as an Element) to the List

mixed_list = [{1, 2}, [5, 6, 7]]


# number tuple
number_tuple = (3, 4)
# inserting a tuple to the list
mixed_list.insert(1, number_tuple)
print('Updated List:', mixed_list)

Output

Updated List: [{1, 2}, (3, 4), [5, 6, 7]]

4. + operator
Unit 3: Data Structures in Python

The most conventional method to perform the list concatenation, the use of “+” operator
can easily add the whole of one list behind the other list and hence perform the concatenation.

Example1:
list1 = [1, 4, 5, 6, 5]
list2= [3, 5, 7, 2, 5]
# using + operator to concat
list1 = list1 + list2
# Printing concatenated list
print("concatenated list"+str(list1))

Output:
concatenated list[1, 4, 5, 6, 5, 3, 5, 7, 2, 5]

5. * operator

The most conventional method to perform the list concatenation, the use of “+” operator can easily
add the whole of one list behind Using * operator

Using * operator, this method is the new addition to list concatenation and works only in Python
3.6+. Any no. of lists can be concatenated and returned in a new list using this operator.

Example1 :-

test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]

# using * operator to concat


res_list = [*test_list1, *test_list2]

# Printing concatenated list


print ("Concatenated list using * operator : "
+ str(res_list))
Output:
Concatenated list using * operator : [1, 4, 5, 6, 5, 3, 5, 7, 2, 5]

Example2:-

list = [1, 4, 5, 6, 5]
print(list *2)

Output:
Unit 3: Data Structures in Python

[1, 4, 5, 6, 5, 1, 4, 5, 6, 5]

Basic list operations (indexing and slicing)

Indexing:
An individual item in the list can be referred by using an index, which is an integer number that
indicates the relative position of the item in the list.

There are various ways in which we can accesses elements in list


1. Positive indexing
2. Negative indexing

1.Positive indexing

Fig: List has seven elements with index 0 to 6


Example :for positive indexing
>>>list=[10,20,30,40,50]
>>>list[0]
10
>>>list[3:]
[40,30]
>>>list[:4]
[10,20,30,40]
>>>list[5]
traceback (most recent call last):
File "main.py", line 2, in <module>
print(list[5])
IndexError: list index out of range

2. Negative Indexing

Now, let us look at the below diagram which illustrates a list along with its negative indexes.

Fig: List with negative index


Unit 3: Data Structures in Python

Example1:
>>>list=[‘p’,’y’,’t’,’h’,’o’,’n’]
>>>list[-1]
‘n’
>>>list[-6]
‘p’
>>>list[-3:]
[’h’,’o’,’n’]

>>>list[-7]
traceback (most recent call last):
File "main.py", line 2, in <module>
print(list[5])
IndexError: list index out of range

List Slicing

In Python, list slicing is a common practice and it is the most used technique for
programmers to solve efficient problems. Consider a python list, In-order to access a range of
elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator
i.e. colon(:)

With this operator, one can specify where to start the slicing, where to end, and specify the step.
List slicing returns a new list from the existing list.

Syntax:

Lst[ Initial : End : IndexJump ]

If Lst is a list, then the above expression returns the portion of the list from index Initial to index
End, at a step size IndexJump.

Example :for List slicing


>>>list=[10,20,30,40,50]
>>>list[1:4]
[20,30,40,50]
>>>list[2:5]
[ 30,40,50]

List slicing with step size


Unit 3: Data Structures in Python

Step is an integer value which determines the increment between each index for slicing
Syntax
List_name[start_index:end_index:step_size]

>>>a = [1, 2, 3, 4, 5, 6, 7, 8]
>>>print(a[:5]) # prints [1, 2, 3, 4, 5]
>>>print(a[2:]) # prints [3, 4, 5, 6, 7, 8]
>>>print(a[2:5]) # prints [3, 4, 5]
>>>print(a[2:7:2]) # prints [3, 5, 7]

Traversing a list
Means accessing all the elements or items in the list ,it can be performed by using any conditional
statement in python

Example
>>>a = [10, 20, 30]
for x in a
print(x)

Output
10
20
30

Build in functions and methods for list


Python includes the following list functions –

Sr. Function with Description Example


No

list1 = [123, 'xyz', 'zara']


len(list) print "list length : ", len(list1)
1
Gives the total length of the list.p> output
list length : 3

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456,


700, 200]
print "Max value element : ", max(list1)
max(list) print "Max value element : ", max(list2)
2
Returns item from the list with max value. output
Max value element : zara
Max value element : 700
Unit 3: Data Structures in Python

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456,


700, 200]
print "min value element : ", min(list1)
min(list) print "min value element : ", min(list2)
3
Returns item from the list with min value. Output
min value element : 123
min value element : 200

aTuple = (123, 'xyz', 'zara', 'abc');


aList = list(aTuple)
list(seq)
4 print "List elements : ", aList
Converts a tuple into list.
Output
List elements : [123, 'xyz', 'zara', 'abc']

Python includes following list methods

Sr.No Methods with Description Example

1 list.append(obj) aList = [123, 'xyz', 'zara', 'abc'];


Appends object obj to list aList.append( 2009 );
print "Updated List : ", aList
output-
Updated List : [123, 'xyz', 'zara', 'abc', 2009]

2 list.count(obj) aList = [123, 'xyz', 'zara', 'abc', 123];


Returns count of how many times obj print "Count for 123 : ", aList.count(123)
occurs in list print "Count for zara : ", aList.count('zara')
Output −
Count for 123 : 2
Count for zara : 1

3 list.extend(seq) aList = [123, 'xyz', 'zara', 'abc', 123];


Appends the contents of seq to list bList = [2009, 'manni'];
aList.extend(bList)
print "Extended List : ", aList

Output-
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009,
'manni']
Unit 3: Data Structures in Python

4 list.index(obj) aList = [123, 'xyz', 'zara', 'abc'];


Returns the lowest index in list that print "Index for xyz : ", aList.index( 'xyz' )
obj appears print "Index for zara : ", aList.index( 'zara' )
Output −
Index for xyz : 1
Index for zara : 2

5 list.insert(index,obj) List = [123, 'xyz', 'zara', 'abc']


Inserts object obj into list at offset aList.insert( 3, 2009)
index print "Final List : ", aList
Output −
Final List : [123, 'xyz', 'zara', 2009, 'abc']

6 list.pop(obj=list[-1]) List = [123, 'xyz', 'zara', 'abc'];


Removes and returns last object or obj print "A List : ", aList.pop()
from list print "B List : ", aList.pop(2)
Output −
A List : abc
B List : zara

7 list.remove(obj) aList = [123, 'xyz', 'zara', 'abc', 'xyz'];


Removes object obj from list aList.remove('xyz');
print "List : ", aList
aList.remove('abc');
print "List : ", aList
Output −
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']

8 list.reverse() aList = [123, 'xyz', 'zara', 'abc', 'xyz'];


Reverses objects of list in place aList.reverse();
print "List : ", aList
Output −
List : ['xyz', 'abc', 'zara', 'xyz', 123]

9 list.sort([func]) aList = [123, 'xyz', 'zara', 'abc', 'xyz'];


Sorts objects of list, use compare func aList.sort();
if given print "List : ", aList
Output −
List : [123, 'abc', 'xyz', 'xyz', 'zara']
Unit 3: Data Structures in Python

Tuples
● A tuple is a liner data structurer.
● A python tuple is a sequence of data value called as items or elements
● A Tuple is a data structure that is an immutable or unchangeable ordered sequence e of
elements/items because tuples are immutable their values cannot be modified
● A tuple is a heterogeneous data structure and used for grouping data. Each element or value
that is inside a tuple is called an item
● In python tuple is written in round bracket value of tuple can be assessed from its index,
which are integer start from 0.

Difference between tuples and list

Sr.No List Tuple

1 Lists are mutable Tuples are immutable

The implication of iterations is


2 Implication of iterations is Time-consuming comparatively Faster

The list is better for performing operations, Tuple data type is appropriate for
3 such as insertion and deletion. accessing the elements

Tuple consume less memory as


4 Lists consume more memory compared to the list

Tuple does not have many built-in


5 Lists have several built-in methods methods.

The unexpected changes and errors are more


6 likely to occur In tuple, it is hard to take place.
Unit 3: Data Structures in Python

Creating Tuple
To create a tuple in Python, place all the elements in a () parenthesis, separated by commas.
A tuple can have heterogeneous data items, a tuple can have string and list as data items as
well.

Syntax for defining tuple is python is


<tuple_name>=(val1,val2,val3…….valn)
Here tuple name indicates name of yuples and val1,val2,val3……valn indicates values
assigned to tuple

Example1

Emp(20,”abc”,’m’,50)

Example2

# An empty tuple
empty_tuple = ()
print (empty_tuple)
Output:
()

# Creating non-empty tuples

# One way of creation


tup = 'python', 'geeks'
print(tup)

Output
('python', 'tuple')

# Another for doing the same


tup = ('python', 'tuple')
print(tup)

Output
('python', 'tuple')

#Create a tuple with different data types

tuplex = ("tuple", False, 3.2, 1)


print(tuplex)
Unit 3: Data Structures in Python

Output:

('tuple', False, 3.2, 1)

Tuple assignment

It allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the
right of the assignment.
Example 1:
>>>Tup1=(11,”vaishali”,”Pune”)
>>>(id,name,city)=tup1
>>>Print(id)
11
>>>Print(name)
vaishali

Example2:
It is useful to swap the values of two variables. With conventional assignment statements, we have
to use a temporary variable. For example, to swap a and b:

Swap two numbers


a=2;b=3
print(a,b)
temp = a
a=b
b = temp
print(a,b)

Output:

(2, 3)
(3, 2)

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. For example −

Example 1:

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
Unit 3: Data Structures in Python

Output

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following example demonstrates −

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

# Following action is not valid for tuples


# tup1[0] = 100;

# So let's create a new tuple as follows


tup3 = tup1 + tup2;
print tup3;

output

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong with
putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement. For example −

tup = ('physics', 'chemistry', 1997, 2000);


printtup;
Unit 3: Data Structures in Python

deltup;
print "After deleting tup : ";
printtup;

This produces the following result. Note an exception raised, this is because after deltup tuple does
not exist anymore −

('physics', 'chemistry', 1997, 2000)


After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
printtup;
NameError: name 'tup' is not defined

We can convert tuple into a list ,remove the item and convert back to a tuple
Tup1=(1,2,3,4,5)
List1=list(tup1)
Del list[2]0
B=typle(list)
Print(b)

Output
(1,2,4,5)

Tuple operations
There are three following sequence operations

1. Concatenation and repetitions (+, *)

The + operator creates a new tuple as the concatenation of the arguments. Here's an example.

>>>
("chapter",8) + ("strings","tuples","lists")

('chapter', 8, 'strings', 'tuples', 'lists')

The * operator between tuples and numbers (number * tuple or tuple * number) creates a new tuple that is
a number of repetitions of the input tuple.

>>>
2*(3,"blind","mice")

(3, 'blind', 'mice', 3, 'blind', 'mice')

2. Membership function
Unit 3: Data Structures in Python

We can test an item is in tuple or not using membership function (in)

>>>t=(10,20,30,50)
>>> 30 in t
True
>>>25 in t
False

Built in functions and methods of tuples

Following table shows built in functions in pythons

Python includes the following tuple functions −

Sr.No. Function & Description Example

1 len(tuple)

Gives the total length of the tuple. tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')

print ("First tuple length : ", len(tuple1))

print ("Second tuple length : ", len(tuple2))

Output−

First tuple length : 3

Second tuple length : 2

2 max(tuple) tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700,


200)
Returns item from the tuple with
max value. print ("Max value element : ", max(tuple1))

print ("Max value element : ", max(tuple2))

Output −

Max value element : phy

Max value element : 700


Unit 3: Data Structures in Python

3 min(tuple) tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700,


200)
Returns item from the tuple with
min value. print ("min value element : ", min(tuple1))

print ("min value element : ", min(tuple2))

Output −

min value element : bio

min value element : 200

4 tuple(seq) list1 = ['maths', 'che', 'phy', 'bio']

Converts a list into tuple. tuple1 = tuple(list1)

print ("tuple elements : ", tuple1)

Output −

tuple elements : ('maths', 'che', 'phy', 'bio')

Python has two built-in methods that you can use on tuples.

Method Description Example

count() Returns the number of times a specified >>>tup1(1,2,3,2,4)


value occurs in a tuple
>>tup1.count(2)

index() Searches the tuple for a specified value and >>>tup1(1,2,3,2,4)


returns the position of where it was found
>>tup1.index(3)

Set
Unit 3: Data Structures in Python

Mathematically a set is a collection of items not in any particular order. A Python set is similar to
this mathematical definition with below additional conditions.

 The elements in the set cannot be duplicates.

 The elements in the set are immutable (cannot be modified) but the set as a whole is
mutable.

 There is no index attached to any element in a python set. So they do not support any
indexing or slicing operation.
A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
Python’s set class represents the mathematical notion of a set. The major advantage of using a
set, as opposed to a list, is that it has a highly optimized method for checking whether a specific
element is contained in the set. This is based on a data structure known as a hash table. Since sets
are unordered, we cannot access items using indexes like we do in lists
A set is a collection which is both unordered and unindexed.Setsare written with curly brackets.

Creating a set
A set is created by using the set() function or placing all the elements within a pair of curly braces.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)

When the above code is executed, it produces the following result. Please note how the order of
the elements has changed in the result.

set(['Wed','Sun','Fri','Tue','Mon','Thu','Sat'])
set(['Jan','Mar','Feb'])
set([17,21,22])
Unit 3: Data Structures in Python

Accessing Values in a Set


We cannot access individual values in a set. We can only access all the elements together as
shown above. But we can also get a list of individual elements by looping through the set.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])

for dinDays:
print(d)
When the above code is executed, it produces the following result.
Wed
Sun
Fri
Tue
Mon
Thu
Sat
Adding Items to a Set
We can add elements to a set by using add() method. Again as discussed there is no specific index
attached to the newly added element.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

Days.add("Sun")
print(Days)

When the above code is executed, it produces the following result.


set(['Wed','Sun','Fri','Tue','Mon','Thu','Sat'])
Removing Item from a Set
We can remove elements from a set by using discard() method. Again as discussed there is no
specific index attached to the newly added element.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Unit 3: Data Structures in Python

Days.discard("Sun")
print(Days)
When the above code is executed, it produces the following result.
set(['Wed','Fri','Tue','Mon','Thu','Sat'])

Adding items to the set


Python provides the add() method and update() method which can be used to add some particular item to
the set. The add() method is used to add a single element whereas the update() method is used to add
multiple elements to the set. Consider the following example.

Example: 1 - Using add() method


1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nAdding other months to the set...");
5. Months.add("July");
6. Months.add ("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)
Output:

printing the original set ...


{'February', 'May', 'April', 'March', 'June', 'January'}

Adding other months to the set...

Printing the modified set...


{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

looping through the set elements ...


February
July
May
April
March
August
June
January
Unit 3: Data Structures in Python

To add more than one item in the set, Python provides the update() method. It accepts iterable as an
argument.

Consider the following example.

Example - 2 Using update() function


1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nupdating the original set ... ")
5. Months.update(["July","August","September","October"]);
6. print("\nprinting the modified set ... ")
7. print(Months);
Output:

printing the original set ...


{'January', 'February', 'April', 'May', 'June', 'March'}

updating the original set ...


printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}

Python Set Operations


Set can be performed mathematical operation such as union, intersection, difference, and symmetric
difference. Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.

1.Union of two Sets


The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all
the items that are present in both the sets.

Consider the following example to calculate the union of two sets.

Example 1: using union | operator

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}


2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1|Days2) #printing the union of the sets
Output:
Unit 3: Data Structures in Python

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}


Python also provides the union() method which can also be used to calculate the union of two sets.
Consider the following example.

Example 2: using union() method

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}

2. Intersection of two sets


The intersection of two sets can be performed by the and& operator or the intersection() function. The
intersection of the two sets is given as the set of the elements that common in both sets.

Consider the following example.

Example 1: Using & operator

1. Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday","Tuesday","Sunday", "Friday"}
3. print(Days1&Days2) #prints the intersection of the two sets
Output:

{'Monday', 'Tuesday'}
Example 2: Using intersection() method

1. set1 = {"Devansh","John", "David", "Martin"}


2. set2 = {"Steve", "Milan", "David", "Martin"}
3. print(set1.intersection(set2)) #prints the intersection of the two sets
Output:

{'Martin', 'David'}
Example 3:

1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
Unit 3: Data Structures in Python

{1,2,5}

3. The intersection_update() method


The intersection_update() method removes the items from the original set that are not present in both the
sets (all the sets if more than one are specified).

The intersection_update() method is different from the intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, the intersection() method returns a new
set.

Consider the following example.

1. a = {"Devansh", "bob", "castle"}


2. b = {"castle", "dude", "emyway"}
3. c = {"fuson", "gaurav", "castle"}
4.
5. a.intersection_update(b, c)
6.
7. print(a)
Output:

{'castle'}

4. Difference between the two sets


The difference of two sets can be calculated by using the subtraction (-) operator
or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes the
resulting set will be obtained that element of A, which is not present in the set B.

Consider the following example.

Example 1 : Using subtraction ( - ) operator

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:
Unit 3: Data Structures in Python

{'Thursday', 'Wednesday'}
Example 2 : Using difference() method

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
Output:

{'Thursday', 'Wednesday'}

5.Symmetric Difference of two sets


The symmetric difference of two sets is calculated by ^ operator or symmetric_difference() method.
Symmetric difference of sets, it removes that element which is present in both sets. Consider the following
example:

Example - 1: Using ^ operator

1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:

{3, 4, 5, 6, 8, 9, 10}
Example - 2: Using symmetric_difference() method

1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:

{3, 4, 5, 6, 8, 9, 10}

6. Set comparisons
Unit 3: Data Structures in Python

Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we
can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is
returned depending upon the items present inside the sets.

Consider the following example.

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday"}
3. Days3 = {"Monday", "Tuesday", "Friday"}
4.
5. #Days1 is the superset of Days2 hence it will print true.
6. print (Days1>Days2)
7.
8. #prints false since Days1 is not the subset of Days2
9. print (Days1<Days2)
10.
11. #prints false since Days2 and Days3 are not equivalent
12. print (Days2 == Days3)
Output:

True
False
False

Python Built-in set methods


Python contains the following methods to be used with the sets.

SN Method Description

1 add(item) It adds an item to the set. It has no effect if the


item is already present in the set.

2 clear() It deletes all the items from the set.

3 copy() It returns a shallow copy of the set.

4 difference_update(....) It modifies this set by removing all the items that


are also present in the specified sets.
Unit 3: Data Structures in Python

5 discard(item) It removes the specified item from the set.

6 intersection() It returns a new set that contains only the


common elements of both the sets. (all the sets if
more than two are specified).

7 intersection_update(....) It removes the items from the original set that are
not present in both the sets (all the sets if more
than one are specified).

8 Isdisjoint(....) Return True if two sets have a null intersection.

9 Issubset(....) Report whether another set contains this set.

10 Issuperset(....) Report whether this set contains another set.

11 pop() Remove and return an arbitrary set element that


is the last element of the set. Raises KeyError if
the set is empty.

12 remove(item) Remove an element from a set; it must be a


member. If the element is not a member, raise a
KeyError.

13 symmetric_difference(....) Remove an element from a set; it must be a


member. If the element is not a member, raise a
KeyError.

14 symmetric_difference_update(... Update a set with the symmetric difference of


.) itself and another.
Unit 3: Data Structures in Python

15 union(....) Return the union of sets as a new set.


(i.e. all elements that are in either set.)

16 update() Update a set with the union of itself and others.

Dictionaries:
Accessing values in Dictionary, deleting
values in Dictionary and updating
Dictionary.
Basic Dictionary operations.
Built – in Dictionaries functions

Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with
the key to obtain its value. Following is a simple example −
#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Class':'First'}
print"dict['Name']: ",dict['Name']
print"dict['Age']: ",dict['Age']

When the above code is executed, it produces the following result −


dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error as follows −
#!/usr/bin/python
Unit 3: Data Structures in Python

dict={'Name':'Zara','Age':7,'Class':'First'}
print"dict['Alice']: ",dict['Alice']

When the above code is executed, it produces the following result −


dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying
an existing entry, or deleting an existing entry as shown below in the simple
example –
#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Class':'First'}
dict['Age']=8;# update existing entry
dict['School']="DPS School";# Add new entry

print"dict['Age']: ",dict['Age']
print"dict['School']: ",dict['School']

When the above code is executed, it produces the following result −


dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents of
a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example −
#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Class':'First'}
Unit 3: Data Structures in Python

deldict['Name'];# remove entry with key 'Name'


dict.clear();# remove all entries in dict
deldict;# delete entire dictionary

print"dict['Age']: ",dict['Age']
print"dict['School']: ",dict['School']

This produces the following result. Note that an exception is raised because
after deldict dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for the
keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last assignment
wins. For example −
#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Name':'Manni'}
print"dict['Name']: ",dict['Name']

When the above code is executed, it produces the following result −


dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples
as dictionary keys but something like ['key'] is not allowed. Following is a simple
example −
#!/usr/bin/python
Unit 3: Data Structures in Python

dict={['Name']:'Zara','Age':7}
print"dict['Name']: ",dict['Name']

When the above code is executed, it produces the following result −


Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions −

Sr. Function with Description Example


No
.

1 cmp(dict1, dict2) dict1 =

Compares elements of {'Name':'Zara','Age':7};


both dict. dict2 ={'Name':'Mahnaz','Age':27};
dict3 ={'Name':'Abid','Age':27};
dict4 ={'Name':'Zara','Age':7};
print"Return Value : %d"%cmp(dict1, dict2)
print"Return Value : %d"%cmp(dict2, dict3)
print"Return Value : %d"%cmp(dict1, dict4)

When we run above program, it produces following result −


Return Value : -1
Return Value : 1
Return Value : 0

2 len(dict) Gives the total length of the dictionary. This would be equal
to the number of items in the dictionary.

3 str(dict) Produces a printable string representation of a dictionary

4 type(variable) Returns the type of the passed variable. If passed variable is


dictionary, then it would return a dictionary type.
Unit 3: Data Structures in Python

Python includes following dictionary methods −

Sr.No Methods with Description

1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict's (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10 dict.values()
Returns list of dictionary dict's values

You might also like