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

Unit 2 Python

Bca 3rd sem Bangalore University

Uploaded by

bhuvaneshnair21
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)
80 views

Unit 2 Python

Bca 3rd sem Bangalore University

Uploaded by

bhuvaneshnair21
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/ 33

Unit -2

I. Lists
 Creating Lists
 Basic List Operation
 Indexing and slicing in Lists
 Built-in functions used on Lists
 List Methods
II. Dictionaries
 Creating Dictionary
 Accessing and modifying key: value pair in Dictionaries
 Built-in function used on Dictionary
 Dictionary Methods
III. Tuples and Sets
 Creating Tuples
 Basic Tuple Operations
 Indexing and Slicing in Tuples
 Tuple Methods
 Built-in function used on Tuples
 Difference between List, Tuple, Set, and Dictionary
 Using Zip () Function
 Sets
 Set Methods
 Frozen set
1. Lists
 List is Represent a group of individual objects as a single.
 List objects are mutable i.e., list element(s) are changeable. It means that
we can modify the items stored within the list.
 The sequence of various data types is stored in a list. A list is a collection
of different kinds of values or items.
 List is maintained Insertion order.
 It allowed Duplicates Objects.
 It allowed Heterogeneous Objects.
 List is Dynamic Because Based on our requirement we can increase the
size and decrease the size.
 List elements will be placed within square brackets and with comma
separator.
 Python supports both positive and negative indexes. +ve index means
from left to right where as negative index means right to left.

[10,” A”,” B”,20,30,10]

Creating Lists

1.we can create empty list object

list= []
print(list)
print(type(list))
output
[]
<class ‘list’>
2. If we know elements already then we can create list as follows
list=[10,20,30,40]
3. list with dynamic input
list=eval (input ("Enter List:"))
print(list)
print(type(list)
Output:
Enter List: [10,20,30,40]
[10, 20, 30, 40]
<class ‘list’>

4.with list () function

l=list (range (0,10,2))

print(l)

print(type(l))

output

[0,2,4,6,8]

<class ‘list>

Eg: s="durga"

l=list(s)

print(l)

output

[‘d’,’u’,’r’,’g’,’a’]
5. with split () function

s="Learning Python is very very easy !!!"

l=s. split ()

print(l)

print(type(l))

output

['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']

<class ‘list’>

Note:

Sometimes we can take list inside another list, such type of lists is called nested
lists.

Example:

# Creating a nested List

nested List = [[6, 2, 8], [1, "Interview bit", 3.5], "preparation"]

Basic List Operation

Let's see the various operations we can perform on the list in Python.

 Concatenation: One list may be concatenated with itself or another list using
‘+’ operator.

Example:

List1 = [1, 2, 3, 4]

List2 = [5, 6, 7, 8]
concat_List = List1 + List2

print(concat_List)

output:

[1, 2, 3, 4, 5, 6, 7, 8]

 Repeating the elements of the list: We can use the ‘*’ operator to repeat the
list elements as many times as we want.

Example:

my List = [1, 2, 3, 4]

print (my List*2)

Output:

[1, 2, 3, 4, 1, 2, 3, 4]

 Membership Check of an element in a list: We can check whether a specific


element is a part/ member of a list or not.
 Two types in operator and not in operator.

Example:

my List = [1, 2, 3, 4, 5, 6]

print (3 in my List)

print (10 in my List)

print (10 not in my List)

Output:

True

False

True
 Iterating through the list: We can iterate through each item within the list by
employing a for a loop.

Example:

my List = [1, 2, 3, 4, 5]

for n in my List:

print(n)

output:

 Finding the length of List in python: len () method is used to get the length of
the list.

Example:

my List = [1, 2, 3, 4, 5]

print (len (my List))

output:

5
Accessing elements of List

We can access elements of the list either by using index or by using slice operator (:).

1.By using index:

 Elements stored in the lists are associated with a unique integer number known
as an index.
 The first element is indexed as 0, and the second is 1, and so on. So, a list
containing six elements will have an index from 0 to 5.
 For accessing the elements in the List, the index is mentioned within the index
operator ([ ]) preceded by the list's name.
 Another way we can access elements/values from the list in python is using a
negative index. The negative index starts at -1 for the last element, -2 for the last
second element, and so on.

Example:

My List = [3, 4, 6, 10, 8]

# Accessing values stored in lists using positive index

print ("Values accessed using positive Index.")

print (My List [2])


print (My List [4])

# Accessing values stored in lists using negative index

print ("Values accessed using negative Index.")

print (My List [-1])

print (My List [-5])

Output:

Values accessed using positive Index.

Values accessed using negative Index.

2. By using Slice Operator

 In Python, we can access the elements stored in a range of indexes using


the slicing operator (:). The index put on the left side of the slicing
operator is inclusive, and that mentioned on the right side is excluded.
 Slice itself means part of something. So, when we want to access elements
stored at some part or range in a list, we use slicing.

Syntax:

list2= list1[start: stop: step]

start ==>it indicates the index where slice has to start default value is 0.
stop ===>It indicates the index where slice has to end default value is max allowed
index of list i.e. length of the list.

step ==>increment value default value is 1

Example:

my List = ['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']

# Accessing elements from index beginning to 5th index

print (my List [:6])

# Accessing elements from index 3 to 6

print (my List [3:7])

# Accessing elements from index 5 to end

print (my List [5:])

# Accessing elements from beginning to end

print (my List [:])

# Accessing elements from beginning to 4th index

print (my List [: -6])

output:

['i', 'n', 't', 'v', 'i', 'e']

['v', 'i', 'e', 'w']

['e', 'w', 'b', 'i', 't']

['i', 'n', 't', 'v', 'i', 'e', 'w', 'b', 'i', 't']

['i', 'n', 't', 'v']

We can also use slicing to change, remove/delete multiple elements from the list.

List = [1, 2, 3, 4, 5, 6, 7, 8]

print (List)
# Changing elements from index 2nd to 5th

List [2:5] = [1, 1, 1]

print (List)

# Deletion multiple items from the List

del List [2:6]

print (List)

output:

[1, 2, 3, 4, 5, 6, 7, 8]

[1, 2, 1, 1, 1, 6, 7, 8]

[1, 2, 7, 8]

Built-in functions used on Lists

Returns length of the list or size of the list.


len () Syntax:
len (Object)
Example:
list= [10,20,30,40]
Print(len(list))
Output
4
Return maximum element of a given list.
max () Syntax:
max (arg1, arg2, *args [, key])
Example:
list= [10,20,30]
print(max(list))
output
30
Return minimum element of a given list.
min () Syntax: min (a, b, c, …, key=func)
Example:
list= [10,20,30]
print(min(list))
output:10
Return true if any element of the list is true. if the list is
any () empty, return false.
Syntax:
any (list of iterables)
Example:
print (any ([False, False, False, False]))

output
False
Returns True if all the items/elements present within the
all () list are true or if the list is empty.
Syntax:
all (list of iterables)
Example:
print (all ([False, True, True, False]))
output
False
Returns the sum of all the elements present within the list.
sum () Syntax: sum (iterable, start)
Example:
numbers = [1,2,3,4,5,1,4,5]
Sum = sum(numbers)
print (Sum)
Output:
25
Test each element of the list as true or not on the function
filter () passed as an argument thereto and returns a filtered
iterator.
Syntax: filter (function, sequence)
Example:
numbers= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(num):
return num % 2 == 0
even_numbers = list (filter (is_even, numbers))
print ("Even numbers:", even_numbers)
Returns a list after applying the function passed as an
map () argument to every element of the iterable.
Syntax: map (function, iterator)
Example:
list1 = [1, 2, 4, 3]
list2 = [1, 2, 5, 8]
list3 = [1, 2, 5, 8, 10]
list4 = [1, 2, 4, 3]
print cmp (list2, list1)
print cmp (list2, list3)
print cmp (list4, list1)

This function returns 1 if the first list is “greater” than


cmp () the second list.
Syntax: cmp (list1, list2)
Example:
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
result = map (addition, numbers)
print(list(result))
List Methods

append () Add an element to the end of the list.


Syntax: list. append(item)
Example:
my_list = ['geeks', 'for']
my_list. append('geeks')
print (my_list)
Add items of one list to another list.
extend () Syntax: list. extend(iterable)
Example:
my_list = ['geeks', 'for']
another list = [6, 0, 4, 1]
my_list. extend (another list)
print (my_list)
Adds an item at the desired index position.
insert () Syntax: list. insert (index, element)
Example:
List= [10,20,30,40]
List.insert(3,89)
print (List)
Remove the primary item from the list with the required
remove () value.
Syntax: list. remove(element)
Example:
list= [10 ,20,30]
list. remove (20)
print(list)
Remove the item from the required index within the list, and
pop () return it.
Syntax: list. pop ()
Example:
n= [10,20,30,40]
print (n.pop ())
Remove all items from the list.
clear () Syntax: list. clear ()
Example:
n= [10,20,30,40]
n. clear ()
Returns 0-based index of the first matched item. Raises Value
index () Error if an item isn’t found within the list.
Syntax: list. index (index)
Example:
n= [0,1,2,3,4,5]
print (n. index (2))
Return a shallow copy of the list i.e. two lists share the
copy () identical elements via reference.
Syntax: list. copy ()
Example:
fruits = ["mango","apple","strawberry"]
shakes = fruits. copy ()
print(shakes)
Returns the frequency of an element appearing in the list.
count () Syntax: list_name. count(object)
Example:
fruits = ["Apple", "Mango", "Banana", "Cherry”]
print (fruits. count("Apple"))
2. Dictionaries

 Dictionaries in Python is a data structure, used to store values in key: value


format. This makes it different from lists, tuples, and arrays as in a dictionary
each key has an associated value.
 Dictionary is mutable.
 The Dictionary is an unordered collection that contain key: value pairs.
 If we want to represent a group of object as key value pairs then we should go
for dictionary.
 Duplicate Keys are not allowed but values can be duplicated.
 Heterogeneous objects are allowed for both keys and values.
 Insertion order is not maintained.
 Dictionaries are Dynamic. Because based on our requirement we can increase
the size and decrease the size.
 In Dictionary Indexing and Slicing Concepts are not applicable.
Syntax: dict_var = {key1: value1, key2: value2, ….}
Example:
dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(dict)

Creating Dictionary

In a dictionary can be created by placing a sequence of elements within


curly {} braces, separated by a ‘comma’.

1) d= {}

2) d=dict ()

we are creating empty dictionary. We can add entries as follow

d[100]="durga"

d[200]="ravi"
d[300]="shiva"

print(d) # {100: 'durga', 200: 'ravi', 300: 'shiva'}

Accessing and modifying key: value pair in Dictionaries

To access the items of a dictionary, refer to its key name. Key can be used inside
square brackets.

Example:

my_dict={'Name':'Ravi',"Age":'32','ID':'258RS569'}

print(my_dict['ID']) #accessing using the ID key

print(my_dict['Age']) #accessing using the Age

output:

258RS569

32

If we tried to reference a key that is not present in our Python dictionary, we would get
the following error

Example:

print(my_dict['Phone']) #accessing using a key that is not present

output:

Key Error: 'Phone'

print(my_dict['Phone'])

Line 4 in <module> (Solution.py)


Access a Value in Dictionary using get () in Python

The code demonstrates accessing a dictionary element using the get () method. It
retrieves and prints the value associated with the key 3 in the dictionary ‘Dict’.

Example:

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


print (Dict.get (3))

Updating Dictionary in Python

We can do multiple things when trying to update a dictionary in Python.

Syntax: d[key]=value

1. Add a new entry.


2. Modify an existing entry.
3. Adding multiple values to a single key.
4. Adding a nested key.

Example:
#creating an empty dictionary
my_dict= {}
print(my_dict)
#adding elements to the dictionary one at a time
my_dict [1] ="James"
my_dict [2] ="Jim"
my_dict [3] ="Jake"
print(my_dict)
#modifying existing entry
my_dict [2] ="Apple"
print(my_dict)
#adding multiple values to a single key
my_dict [4] ="Banana, Cherry, Kiwi"
print(my_dict)
#adding nested key values
my_dict [5] = {'Nested’: {'1’: 'Scaler', '2’: 'Academy'}}
print(my_dict)

Output:
{}
{1: 'James', 2: 'Jim', 3: 'Jake'}
{1: 'James', 2: 'Apple', 3: 'Jake'}
{1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana, Cherry, Kiwi'}
{1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana, Cherry, Kiwi', 5: {'Nested': {'1': 'Scaler',
'2': 'Academy'}}}

Deleting Elements using ‘del’ Keyword

The items of the dictionary can be deleted by using the del keyword as given below.

Syntax: del dictionary_name or del d[key]

Example:
my_dict= {1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana, Cherry, Kiwi'}
del my_dict [4]
print(my_dict)

Output:
{1: 'James', 2: 'Apple', 3: 'Jake'}

Built-in function used on Dictionary

The dictionary's length is returned via the len () function in


len () Python.
Syntax: len(dict)
Example:

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


len(dict)
Output:
4
It returns true if any key in the dictionary is true.
any () Syntax: any(dict)
Example:

dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


any ({'':'','':'','3':''})

output:
True
It returns true if all the keys in the dictionary are true.
all () Syntax: all(dict)
Example:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
all ({1:'',2:'','':''})
Output
False
It returns a new sorted list of keys in a dictionary.
sorted () Syntax: sorted(dict)
Example:

dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}


sorted(dict)

Output

[1,5,7,8]

Dictionary Methods

Remove all the elements from the dictionary.


clear () Syntax: dict. clear ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


print (dict. clear ())
Output:
{}
It returns a copy of the dictionary.
copy () Syntax: dict. copy ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


dict_demo = dict. copy ()
print(dict_demo)

Output:

{1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart”}


It removes an element from the specified key.
pop () Syntax: dict.pop ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


dict_demo = dict. copy ()
x = dict_demo.pop (1)
print(x)
Output:
{2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
removes the most recent key-value pair entered.
popitem () Syntax: dict. popitem ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


dict_demo. popitem ()
print(dict_demo)
Output:
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
keys () It returns the list of keys of the dictionary.
Syntax: dict. keys ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


print (dict. keys ())
Output:
dict_keys ([1, 2, 3, 4, 5])
It is used to get the value of the specified key.
get () Syntax: dict.get ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


print (dict. get (3))
Output:
Facebook
It returns the list of dictionary tuple pairs.
items () Syntax: dict. items ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


print (dict. items ())
Output:
dict_items ([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5,
'Flipkart')])
It returns all the values of the dictionary with respect to given input.
values () Syntax: dict. values ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


print (dict. values ())
Output:
dict_values (['Hcl', 'WIPRO', 'TCS'])

It adds the dict2’s key-value pairs to dict.


Syntax: dict. update(dict2)
update ()
Example:

dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


dict. update ({3: "TCS"})
print(dict)
Output:
{1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}
Tuples

 Tuple is exactly same as List except that it is immutable. i.e. once we create
Tuple object, we cannot perform any changes in that object.
 The sequence of values stored in a tuple can be of any type, and they are
indexed by integers.

 Each element in a tuple has a specific order that will never change because tuples
are ordered sequences.
 Tuples are defined by enclosing elements in parentheses (), separated by a
comma.
 Insertion Order is preserved.
 Duplicates are allowed.
 Heterogeneous objects are allowed.
 We can preserve insertion order and we can differentiate duplicate objects by
using index. Hence index will play very important role in Tuple also.

Creating Tuples
1. t= () creation of empty tuple
2. t= (10,)
t=10,
creation of single valued tuple, parenthesis are optional, should ends with comma
3.t=10,20,30
t= (10,20,30) creation of multi values tuples & parenthesis are optional
4. By using tuple () function:
list= [10,20,30]
t=tuple(list)
print(t)
t=tuple (range (10,20,2))
print(t)
Deleting a Tuple
Example:
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1

print (Tuple1)

Example 1:

tpl= () # empty tuple


print(tpl) #output: ()

Example 2:

employee= (1, 'Steve', True, 25, 12000) # heterogeneous data tuples


print(employee) #output:(1, 'Steve', True, 25, 12000)

Example 3:

Tuples cannot be declared with a single element unless followed by a comma.

tempTuple = ('apple')
print(type(tempTuple)) # OUTPUT: <class ‘str’>
tempTuple = ('apple',)
print(type(tempTuple)) # OUTPUT: <class ‘tuple’>
tempTuple = 'apple',
print(type(tempTuple)) # OUTPUT: <class ‘tuple’>

Indexing and Slicing in Tuples

Indexing

Python allows you to access elements of a collection via negative indices. When
accessing using a negative index, -1 depicts the last element, and -n depicts the first
index where n is the length of the index.
Example:

tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day')

print (tempTuple [2]) # interview

print (tempTuple [-6]) # interview

Slicing in Tuples

Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a


Tuple. Slicing can also be done to lists and arrays. Indexing in a list result to
fetching a single element whereas Slicing allows to fetch a set of elements.

Slice syntax: tuple [start: stop: step]

 start: is the starting index of the string, on which slicing operation has to be
performed. It determines from were slicing of the string will ‘begin’.
 stop: is the stopping index of the slicing, ‘until’ which slicing operation has to
be performed i.e. stop index is excluded while generating the sub-tuple.
 step: It is an optional argument that defines the steps when iterating the list i.e.
it allows us to skip over elements.

Example:
Tuple1 = tuple('GEEKSFORGEEKS')

# Removing First element


print (Tuple1[1:])

# Reversing the Tuple


print (Tuple1[::-1])

# Printing elements of a Range


print (Tuple1[4:9])

Output:
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
Tuple after sequence of Element is reversed:
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
Printing elements between Range 4-9:
('S', 'F', 'O', 'R', 'G')

Tuple Methods

1) index ()

index () method searches for a given element from the start of the list and returns
the position of the first occurrence.

Syntax:

tuple_name.index(element, start, end)

Parameters:
 element – The element whose lowest index will be returned.
 start (Optional) – The position from where the search begins.
 end (Optional) – The position from where the search ends.

Example:
t= (10,20,10,10,20)
print (t. index (10)) #0
2) count ()
count () method returns the count of the occurrences of a given element in a
list.
Syntax:
tuple_name. count(object)

Example:
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
res = T1. count (2)
print (res)

Built-in function used on Tuples


Difference between List, Tuple, Set, and Dictionary
Using Zip () Function

 zip () method takes iterable containers and returns a single iterator object,
having mapped values from all the containers.
 Python's zip () function is a built-in function that is used to combine two or
more iterables into a single iterable.
 This function takes in any number of iterables (lists, tuples, sets, etc.) as
arguments and returns an iterator that aggregates elements from each of the
iterables into tuples.
 Each tuple contains the i-th element from each of the input iterables.

Syntax: zip(*iterators)
Parameters: Python iterable or containers (list, string etc)
Return Value: Returns a single iterator object.

zip () with lists

the zip () function is used to combine two or more lists (or any other iterables) into
a single iterable, where elements from corresponding positions are paired together.

Example:
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha”]
roll_no = [ 4, 1, 3, 2]
# using zip () to map values
mapped = zip (name, roll_no)
print(set(mapped))

Output:
{('Nikhil', 1), ('Shambhavi', 3), ('Manjeet', 4), ('Astha', 2)}

zip () with Dictionary


The zip () function in Python is used to combine two or more iterable dictionaries into
a single iterable, where corresponding elements from the input iterable are paired
together as tuples.
Example:
stocks = ['GEEKS', 'For', 'geeks']
prices = [2175, 1127, 2750]

new_dict = {stocks: prices for stocks,


prices in zip (stocks, prices)}
print(new_dict)

Output:
{'GEEKS': 2175, 'For': 1127, 'geeks': 2750}

zip () with Tuple


zip () works by pairing the elements from tuples based on their positions.
Example:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
zipped = zip (tuple1, tuple2)
result = list(zipped)
print(result)

Sets

 If we want to represent a group of unique values as a single entity then we should


go for set.
 Duplicates are not allowed.
 Insertion order is not preserved. But we can sort the elements.
 Indexing and slicing not allowed for the set.
 Heterogeneous elements are allowed.
 Set objects are mutable i.e. once we create set object, we can perform any
changes in that object based on our requirement.
 We can represent set elements within curly braces and with comma separation.
 We can apply mathematical operations like union, intersection, difference etc on
set objects.

Creation of Set

There are two ways of creating a set

1. Putting all the elements inside curly braces “{“and “}”


2. Using set () method.

Example1:

s= {10,20,30,40}

print(s)

print(type(s))

Output

{40, 10, 20, 30}

We can create set objects by using set () function

Syntax: set([iterable])

set () takes an iterable as an argument. In python, string, lists, and dictionaries are
iterable so you can pass them inside set ().

Example:

setWithMethod = set ([1, 2, 'three'])

print(setWithMethod)
Set Methods

Adding Items in a Python Set

1. add () allows adding single element

Syntax: set.add(element)

2. update () allows to add multiple elements. takes an iterable like string, list,
dictionary as an argument.

Syntax: set. update(iterable)

Example:

initialSet = {1, 2}

initialSet.add (3)

print(initialSet)

toAdd = [4, 5]

initialSet.update(toAdd)

print(initialSet)

Output:

{1, 2, 3}

{1, 2, 3, 4, 5}

Removing Items from a Set in Python

For removing elements, we have these methods:

1. remove(element) - This method removes the element from the set. If the
element is not present then it will throw an error.

Syntax: set. remove(element)

2. discard(element) - This method removes the element from the set. If the
element is not present then the set will remain unchanged.

Syntax: set. discard(element)


3. clear () - This method is used to delete all the set elements.

Syntax: set. clear ()

Example:

mySet = {1, 2, 3, 5}

print ("Before: ", mySet)

mySet.remove(3)

print ("After: ", mySet)

mySet.discard(4)

print ("Using discard: ", mySet)

mySet.clear()

print(mySet)

Output:

Before: {1, 2, 3, 5}

After: {1, 2, 5}

Using: {1, 2, 5}

set ()

4.pop ()

set pop () removes any random element from the set and returns the removed
element.

Syntax: set.pop ()

Example:

s1 = {9, 1, 0}
s1.pop ()
print(s1)

Ouput:

{9, 1}
5.copy ()

The copy () method returns a shallow copy of the set-in python.

Syntax: set. copy ()

Example:

set1 = {1, 2, 3, 4}
# function to copy the set
set2 = set1.copy()
# prints the copied set
print(set2)

output:
{1, 2, 3, 4}

Frozen set

 Frozen set is a built-in data type in Python. It is a set that is immutable (once
defined, cannot be changed).
 It supports all non-modifying operations of the set. Operations like add () won’t
work in the case of a frozen set.
 Frozen sets in Python are immutable objects that only support methods and
operators that produce a result without affecting the frozen set or sets to
which they are applied.
 If no parameters are passed, it returns an empty frozen set.
Syntax: frozenset(iterable_object_name)

Example:

# Creating a Set
String = ('G', 'e', 'e', 'k', 's', 'F', 'o', 'r')
Fset1 = frozenset (String)
print (Fset1)
# No parameter is passed
print (frozenset ())

Output:
frozenset ({'F', 's', 'o', 'G', 'r', 'e', 'k'})
frozenset ()

You might also like