CHAPTER 3
Data Structures in
Python
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Python has four basic inbuilt data structures
namely Lists, Tuple, Dictionary and Set.
1) Lists
2) Tuple
3) Dictionary
4) Set
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Like a string, a list is a sequence of values. In a string,
the values are characters; in a list, they can be any type.
The values in list are called elements or sometimes items.
There are several ways to create a new list; the
simplest is to enclose the elements in brackets “[ ]”.
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Example 1:
# Creating a List
List = []
print("Blank List: ", List)
Output:
Blank List : []
Example 2:
# Creating List of numbers
List = [10, 20, 30]
print(“List of numbers: ", List)
Output:
List of numbers: : [10, 20, 30]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Example 3:
# Creating a List of strings and accessing using index
List = ["Programming", "in", "Python"]
print("List Items: ")
print(List[0])
print(List[2])
Output:
List Items:
Programming
Python
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Example 4:
# Creating a Multi-Dimensional List (By Nesting a list
inside a List)
List = [['Programming', 'in'] , ['Python’]]
print("Multi-Dimensional List: ")
print(List)
Output:
Multi-Dimensional List:
[['Programming', 'in'], ['Python']]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
A list may contain duplicate values with their distinct
positions and hence, multiple distinct or duplicate values
can be passed as a sequence at the time of list creation.
There are several ways to create a new list; the simplest
is to enclose the elements in brackets “[ ]”.
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Example 5:
# Creating a List with the use of Numbers(Having duplicate
values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("List with the use of Numbers: ")
print(List)
Output:
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Example 5:
# Creating a List with mixed type of values (Having numbers
and strings)
List = [1, 2, 'Programming', 4, 'in', 6, 'Python’]
print("List with the use of Mixed Values: ")
print(List)
Output:
List with the use of Mixed Values:
[1, 2, 'Programming', 4, 'in', 6, 'Python']
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Unlike strings, lists are mutable because you can change
the order of items in a list or reassign an item in a list.
When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be
assigned.
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Example 6:
# Updating a List elements (List are mutable)
Numbers = [17, 123]
print("Before: ", Numbers)
Numbers[1] = 5
print("After: ", Numbers)
Output:
Before: [17, 123]
After: [17, 5]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List
Using len() function we can find the length (no. of
elements in list) of list.
Example 7:
# Creating a List of numbers and finding the length
List = [10, 20, 14]
print(len(List))
Output:
3
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Operation
# The + operator concatenates lists
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
Output:
[1, 2, 3, 4, 5, 6]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Operation
# The * operator repeats a list a given number of times
a = [1]
a = a * 3
print(a)
Output:
[1, 1, 1]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Slices
# The slice operator
List = ['a', 'b', 'c', 'd', 'e', 'f']
print(List[1:3])
print(List[:4])
print(List[3:])
Output:
['b', 'c’]
['a', 'b', 'c', 'd’]
['d', 'e', 'f']
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Slices
If you omit the first index, the slice starts at the
beginning. If you omit the second, the slice goes to the
end. So if you omit both, the slice is a copy of the
whole list.
Example 8:
List = ['a', 'b', 'c', 'd', 'e', 'f']
print(List[:])
Output:
['a', 'b', 'c', 'd', 'e', 'f']
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Slices
A slice operator on the left side of an assignment can
update multiple elements.
Example 9:
List = ['a', 'b', 'c', 'd', 'e', 'f']
List[1:3] = ['x', 'y']
print(List)
Output:
['a', 'x', 'y', 'd', 'e', 'f']
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
append() - Adds an element at the end of the list
Example :
fruits = ['apple', 'banana', 'cherry’]
fruits.append(‘orange’)
print(fruits)
Output:
['apple', 'banana', 'cherry’, ‘orange’]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
clear() - Removes all the elements from the list
Example :
fruits = ['apple', 'banana', 'cherry’, ‘orange’]
fruits.clear()
print(fruits)
Output:
[]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
copy() - Returns a copy of the list
Example :
fruits = ['apple', 'banana', 'cherry’, ‘orange’]
X = fruits.copy()
print(x)
Output:
['apple', 'banana', 'cherry’, ‘orange’]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
count() - Returns the number of elements with the
specified value
Example :
fruits = ['apple', 'banana', 'cherry’]
x = fruits.count(‘cherry’)
print(x)
Output:
1
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
extend() - Add the elements of a list (or any iterable),
to the end of the current list.
Example :
fruits = ['apple', 'banana', 'cherry’]
cars = ['Ford', 'BMW', 'Volvo’]
fruits.extend(cars)
print(fruits)
Output:
['apple', 'banana', 'cherry’, 'Ford', 'BMW', 'Volvo’]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
index() - Returns the index of the first element with
the specified value.
Example :
fruits = ['apple', 'banana', 'cherry’, ‘orange’]
x = fruits.index(‘apple’)
print(x)
Output:
0
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
insert() - Adds an element at the specified position.
Example :
fruits = ['apple', 'banana', 'cherry’]
fruits.insert(1,’orange’)
print(fruits)
Output:
['apple’, ‘orange’, 'banana', 'cherry’]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
pop() - Removes the element at the specified position
Example :
fruits = ['apple', 'banana', 'cherry’]
fruits.pop(1)
print(fruits)
Output:
['apple','cherry’]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
remove() - Removes the first item with the specified
value.
Example :
fruits = ['apple', 'banana', 'cherry’]
fruits.remove(‘banana’)
print(fruits)
Output:
['apple', 'cherry’]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
reverse() – Reverses the order of the list.
Example :
fruits = ['apple', 'banana', 'cherry’]
fruits.reverse()
print(fruits)
Output:
['cherry’, 'banana’, 'apple']
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
List Methods
sort() – Sorts the list.
Example :
fruits = ['apple', 'banana', 'cherry’]
fruits.remove(‘banana’)
print(fruits)
Output:
['apple’, ‘banana’, ‘cherry’]
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Tuples
A tuple is a sequence of immutable (A tuple is a
collection which is ordered and unchangeable) Python
objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different
comma-separated values. Optionally you can put these
comma-separated values between parentheses also. For
example
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Tuples
# creating a tuple
tup1 = ('ABC', 'pqr', 1000, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = ("a", "b", "c", "d“)
print(tup1)
print(tup2)
print(tup3)
Output:
('ABC', 'pqr', 1000, 2000)
(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd')
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Tuples
The empty tuple is written as two parentheses
containing nothing
tup1 = ()
To write a tuple containing a single value you have to
include a comma, even though there is only one
value
tup1 = (50,)
Like string indices, tuple indices start at 0, and they
can be sliced, concatenated, and so on.
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Updating 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
# accessing a tuple
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])
Output :
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
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)
o/p: (12, 34.56, 'abc', 'xyz')
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
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
# deleting a tuple
tup = ('ABC', 'pqr', 1997, 2000)
print(tup)
del tup
print("After deleting tup : ")
print(tup)
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Delete Tuple Elements
This produces the following result. Note an exception
raised, this is because after del tup tuple does not
exist any more
('ABC', 'pqr', 1997, 2000)After deleting
tup :-------------------------------------------------------------
--------NameError Traceback (most
recent call last)<ipython-input-54-692273a13f26> in <module>
3deltup; 4print("After deleting tup : ")---->
5print(tup)NameError: name 'tup' is not defined
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Tuple Operations
Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string
Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3)+(4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',)* 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1,2,3) True Membership
for x in (1, 2, 3): print(x) 123 Iteration
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Indexing, Slicing, Matrices
Because tuples are sequences, indexing and slicing work the same way for tuples as
they do for strings. Assuming following input
L = ('spam', 'Spam', 'SPAM!')
Python Expression Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Tuple methods
Because tuples are sequences, indexing and slicing work the same way for tuples as
they do for strings. Assuming following input
L = ('spam', 'Spam', 'SPAM!')
Python Expression Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Tuple methods
Because tuples are sequences, indexing and slicing work the same way for tuples as
they do for strings. Assuming following input
L = ('spam', 'Spam', 'SPAM!')
Method Description
len(tuple) Gives the total length of the tuple
tuple(seq) Converts a list into tuple
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Tuple methods
# len()
Example:
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
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Dictionary
A dictionary is mutable and is another container type
that can store any number of Python objects,
including other container types. Dictionaries consist
of pairs (called items) of keys and their
corresponding values.
Python dictionaries are also known as associative
arrays or hash tables. The general syntax of a
dictionary is as follows:
Ex:
dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Dictionary
Each key is separated from its value by a colon (:), the
items are separated by commas, and the whole thing
is enclosed incurly 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 string s, numbers, or tuples.
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Accessing Values in Dictionary
To access values in dictionary, use the square brackets
for slicing along with the index or indices to obtain
value available at that index. For example
# accessing a dictionary
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print("dict1['Name']: ", dict1['Name'])
print("dict1['Age']: ", dict1['Age'])
print("dict1['Class']: ", dict1['Class'])
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Accessing Values in Dictionary
Output:
dict1[‘Name']: Zara
dict1['Age']: 7
dict1[‘Class']: First
If we attempt to access a data item with a key, which is
not part of the dictionary, we get an error as follows
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print("dict1['Alice']: ", dict1['Alice’])
Output:
KeyError Traceback (most
recent call last)<ipython-input-58-d6f7f5c44745> in <module>
1 dict1 ={'Name':'Zara','Age':7,'Class':'First'};---->
2print("dict1['Alice']: ", dict1['Alice'])KeyError: 'Alice'
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Updating Dictionary
You can update a dictionary by adding a new entry or
item(i.e., a key-value pair), modifying an existing
entry, or deleting an existing entry as shown below in
the simple example
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Updating Dictionary
Example:
# updating dictionary
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict1['Age'] = 8 # update existing entry
dict1['School'] = "LJP" # Add new entry
print ("dict1['Age']: ", dict1['Age'])
print ("dict1['School']: ", dict1['School’])
Output:
dict1['Age']: 8
dict1['School']: LJP
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Deleting Dictionary Elements
To explicitly remove an entire dictionary, just use the del
statement.
# deleting dictionary
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict1['Name'] # remove entry with key 'Name'
dict1.clear() # remove all entries in dict
del dict1 # delete entire dictionary
print("dict1['Age']: ", dict1['Age'])
print("dict1['School']: ", dict1['School'])
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Deleting Dictionary Elements
Output:
NameError Traceback (most
recent call last)<ipython-input-65-8a3a75cd05f3> in
<module> 3 dict1.clear();# remove all entries in dict
4dels ;# delete entire dictionary---->
5print("dict1['Age']: ", dict1['Age']) 6
print("dict1['School']: ", dict1['School'])NameError: name
'dict1' is not defined
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
Method Description
dict.clear() Removes all elements of dictionary dict
dict.copy() Returns a shallow copy of dictionary dict
dict.get(key, default=None) Returns the value of the item with the specified key
dict.items() Returns a list of dict's (key, value) tuple pairs
dict.keys() Returns list of dictionary dict's keys
dict.update(dict2) Adds dictionary dict2's key-values pairs to dict
dict.values() Returns list of dictionary dict's values
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
dict.clear() : Removes all elements of dictionary dict
# clear()
dict = {'Name': 'Zara', 'Age': 7};
print("Start Len : %d" % len(dict))
dict.clear()
print("End Len : %d" % len(dict))
Output :
Start Len : 2
End Len : 0
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
dict.copy(): Returns a shallow copy of dictionary dict
# clear()
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print("New Dictionary : %s" % str(dict2))
Output :
New Dictionary : {'Name': 'Zara', 'Age': 7}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
dict.get() : Returns the value of the item with the specified key
Example:
# get()
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.get('Age'))
print("Value : %s" % dict.get('Education', "Never"))
Output:
Value : 7
Value : Never
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
dict.items(): Returns a list of dict's (key, value) tuple pairs
Example:
# items()
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.items())
Output:
Value :dict_items([('Name', 'Zara'), ('Age', 7)])
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
dict.keys():Returns list of dictionary dict's keys
Example:
# keys()
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.keys())
Output:
Value :dict_keys(['Name', 'Age'])
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
dict.update(dict2):Adds dictionary dict2's key-values pairs to
dict
Example:
# setdefault()
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.setdefault('Age', None))
print("Value : %s" % dict.setdefault('Sex', None))
Output:
Value : 7
Value : None
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Build-in Dictionary Functions & Methods
dict.values():Returns list of dictionary dict's values
Example:
#values()
dict = {'Name': 'Zara', 'Age': 7}
print("Value : %s" % dict.values())
Output:
Value :dict_values(['Zara', 7])
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Set
Sets are used to store multiple items in a single variable. A set
is a collection which is unordered and unindexed. Sets are
written with curly brackets.
# creating set
thisset = {"apple", "banana", "cherry"}
print(thisset)
Output:
{'banana', 'apple', 'cherry’}
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Duplicates Not Allowed in Set
Sets cannot have two items with the same value.
# creating set
thisset = {"apple", "banana", "cherry","cherry"}
print(thisset)
Output:
{'banana', 'apple', 'cherry’}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Set Items - Data Types
Set items can be of any data type.
# string, int and boolean data types
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
A set can contain different data types.
# set with strings, integers and boolean values
set1 = {"abc", 34, True, 40, "male"}
print(set1)
Output:
{True, 'abc', 34, 40, 'male'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Accessing Items 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.
# loop through the set, and print the values
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x, end=",")
Output:
cherry,banana,apple
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Accessing Items in Set
You can also ask if a specified value is present in a set, by using
the in keyword.
# check if "apple" is present in the set:
thisset= {"apple", "banana", "cherry"}
print("apple" in thisset)
Output:
True
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Adding Items in Set
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.
# add an item to a set, using the add() method
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Output:
{'cherry', 'orange', 'banana', 'apple'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Removing Items in Set
To remove an item in a set, use the remove(), or the discard()
method.
# remove "apple" by using the remove() method
thisset= {"apple", "banana", "cherry"}
thisset.remove("apple")
print(thisset)
Output:
{'cherry', 'banana'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure
Removing Items in Set
Remove "apple" by using the discard() method
thisset= {"apple", "banana", "cherry"}
thisset.discard("apple")
print(thisset)
Output:
{'cherry', 'banana'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure The return value of the pop() method is the removed item.
Removing Items in Set
You can also use 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.
# remove the last item by using the pop() method
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
Output:
cherry
{'banana', 'apple'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure The return value of the pop() method is the removed item.
Removing Items in Set
clear() method empties the set.
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Output:
set()
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure The return value of the pop() method is the removed item.
Deleting a Set
del keyword will delete the set completely.
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
Output:
NameError Traceback (most recent call
last)
<ipython-input-24-2ec9feb8cb8a> in <module>
1 thisset = {"apple", "banana", "cherry"}
2 del thisset
----> 3 print(thisset)
NameError: name 'thisset' is not defined
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure The return value of the pop() method is the removed item.
Join the Sets
There are several ways to join two or more sets in Python. You
can use the union() method that returns a new set containing
all items from both sets.
#union() method returns a new set with all items from both
sets
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Output:
{1, 'c', 2, 3, 'a', 'b'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure The return value of the pop() method is the removed item.
Join the Sets
There are several ways to join two or more sets in Python. You
can use the union() method that returns a new set containing
all items from both sets, or the update() method that inserts all
the items from one set into another.
#union() method returns a new set with all items from both
sets
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Output:
{1, 'c', 2, 3, 'a', 'b'}
Dept. of Computer/IT Engineering LJ Polytechnic
Data Structure The return value of the pop() method is the removed item.
Join the Sets
The update() method that inserts all the items from one set
into another.
#update() method inserts the items in set2 into set1
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Output:
{1, 'c', 2, 3, 'a', 'b'}
Note: Both union() and update() will exclude any duplicate items.
Dept. of Computer/IT Engineering LJ Polytechnic