0% found this document useful (0 votes)
2 views84 pages

Python Unit 3

The document provides an overview of data structures in Python, specifically focusing on lists, dictionaries, tuples, and sets. It details how to create and manipulate lists and dictionaries, including operations, built-in functions, and methods associated with each data structure. Additionally, it covers nested lists and various operations such as indexing, slicing, and updating elements.

Uploaded by

Kanchan Patil
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)
2 views84 pages

Python Unit 3

The document provides an overview of data structures in Python, specifically focusing on lists, dictionaries, tuples, and sets. It details how to create and manipulate lists and dictionaries, including operations, built-in functions, and methods associated with each data structure. Additionally, it covers nested lists and various operations such as indexing, slicing, and updating elements.

Uploaded by

Kanchan Patil
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/ 84

UNIT – 3

1. LISTS,
2. DICTIONARIES,
3. TUPLES AND
4. SETS
LISTS DICTIONARIES TUPLES SETS

• Creating Lists; • Creating • Creating • Creating Sets;


• Operations on Dictionaries;
Tuples; • Operations on
Lists; • Operations on
• Built-in Dictionaries; • Operations on Sets;
Functions on • Built-in Tuples; • Built-in
Lists; Functions on
• Implementation Dictionaries; • Built-in Functions on
of Stacks and • Dictionary Functions on Sets;
Queues using Methods; Tuples;
Lists; • Set Methods.
• Populating and • Tuple
• Nested Lists. Traversing
Dictionaries. Methods.
LISTS
• A list is a data structure in Python that is a mutable, ordered sequence of
elements. List is a data structure of collection of elements.
• Lists are defined using square brackets with items separated by commas.

• Mutable: lists are mutable, meaning we can change their values after they
are created.
• Ordered: lists maintains the order in which the elements were added to it.
• Indexing: we can access the elements of a list by their index.
• Slicing: we can extract a subset of elements from a list using slicing which
uses colon to separate a start and end indices.
Creating lists: different ways to create a list in python
1. Using square brackets: we can create a list by enclosing a comma-
separated sequence of values inside square brackets.
For example: my_list = [1, 2, 3, 4, 5]

2. Using list() function: we can create a list by passing a sequence of values


to the list() function.
For example: my_list = list((1, 2, 3, 4, 5))
Creating lists: different ways to create a list in python
3. Using list comprehension: we can create a list using a list comprehension,
which is a very concise way to create a new list by performing an operation on
each item in the existing list. List comprehension is considerably faster than
processing a list using the for loop.
For example: my_list = [x * 2 for x in range(5)]

4. Using range() function: we can create a list of sequential numbers using


the range() function and then convert it to a list using list() function.
For example: my_list = list(range(1,6))
Operations on Lists:
1. Indexing: we can access an individual item in a list using its index value,
which starts at 0.
Example: to access first item in a list.
my_list = [1, 2, 3, 4, 5]
print(my_list(0)) #1

2. Slicing: we can create a new list that contains a subset of the items in the
original list by using slicing. Slicing uses a colon to separate the start and stop
value. Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) #[2, 3, 4]
Operations on Lists:
3. Concatenation: we can combine 2 or more lists into a single list using
concatenation, which uses + operator. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # [1, 2, 3, 4, 5, 6]

4. Repetition: we can create a new list that contains multiple copies of the
items in the original list using repetition, which uses * operator. Example:
my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list) #[1, 1, 1, 2, 2, 2, 3, 3, 3]
Operations on Lists:
5. Length: we can determine the number of items in a list using the len()
function. Example:
mylist = [1, 2, 3, 5, 7]
print(len(mylist)) #5

6. Membership: we can check if an item is in a list using the in keyword.


Example:
my_list = [1, 2, 3]
print(2 in my_list) #True
print(4 in my_list) #False
Operations on Lists:
7. Sorting: we can sort a list in ascending or descending order using the sort(0 method.
Example:
mylist = [3, 2, 1, 4]
mylist.sort()
print(mylist) # [1, 2, 3, 4]
mylist.sort(reverse=True)
print(mylist) # [4, 3, 2, 1]

8. Reversing: we can reverse the order of items in a list using the reverse() method.
Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # [3, 2, 1]
Built-in Functions on Lists:
1. len() 8. count()
2. max() 9. index()
3. min() 10. append()
4. sum() 11. extend()
5. sorted() 12. insert()
6. reversed() 13. remove()
7. list() 14. pop()
15. clear()
Built-in Functions on Lists:
1. len(): This function returns the number of items in a list. Example:
my_list = [1, 3, 2]
print(len(my_list)) #3

2. max(): This function returns the maximum value in a list. Example:


my_list = [1, 3, 2]
print(max(my_list)) #3
my_list2 = [‘abc’, ‘xyz’, ‘pqr’]
print(max(my_list2)) # ‘xyz’
Built-in Functions on Lists:
3. min(): This function returns the minimum value in the list. Example:
my_list = [1, 3, 2, -1]
print(min(my_list)) # -1

4. sum(): This function returns the sum of all the elements in a list. Example:
my_list = [1, 3, 2]
print(sum(my_list)) #3
5. list(): Using list() function, we can convert a sequence (tuple, string) into list.
Example:
tuple = (1, 2, 3, 4)
my_list = list(tuple)
print(my_list) # [1, 2, 3, 4]
Built-in Functions on Lists:
6. sorted(): This function returns a sorted order of list in ascending order.
Example:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(sorted_list)) # [1, 2, 3]

7. reversed(): This function returns reverse iterator of the list. Example:


my_list = [1, 3, 2]
reversed_list = list(reversed(my_list))
print(reversed_list) # [3, 2, 1]
Built-in Functions on Lists:
8. count(e): This function returns the number of occurrences of a specified
element in a list. Example:
my_list = [1, 2, 3, 4, 5, 1]
count = my_list.count(1)
print(count) #2

9. index(e): This function returns the index of the first occurrence of a


specified element in the list. Example:
my_list = [1, 3, 2, 5, 7]
index = my_list.index(3)
print(index) #1
Built-in Functions on Lists:
10. append(e): This function adds an element to the end of the list. Example:
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
print(my_list) # [1, 2, 3, 4, 5, 6]

11. extend(e): This function adds the elements of another list to the end of the
list. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5, 6]
Built-in Functions on Lists:
12. insert(i,e): This function inserts an element at a specified position in the
list. Example:
my_list = [1, 2, 3, 4]
my_list.insert(0, 5)
print(my_list) # [5, 1, 2, 3, 4]
13. remove(e): This function removes the first occurrence of a specified
element in the list. Example:
numbers = [50, 10, 20, 30, 40, 50]
numbers.remove(30)
print(numbers) # [50, 10, 20, 40, 50]
numbers.remove(50)
print(numbers) # [10, 20, 40, 50]
Built-in Functions on Lists:
14. pop(): Using this function element can be removed from the list by specifying the
index value. If the indexed item is not specified then the last item will be deleted
from the list . Example:
my_list = [11, 12, 13, 14, 15]
removed_element = my_list.pop(1)
print(removed_element) # 12
removed_element = my_list.pop()
print(removed_element) # 15

15. clear(): This function removes all the elements from list. Example:
my_list = [1, 3, 2, 5, 7]
my_list.clear()
print(my_list) #[]
Nested Lists:
A Nested list is a list that contains another list as its elements. The elements of
a nested list can be accessed using multiple indices.
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, my_list is a list that contains three other lists as its
elements. The first element is [1, 2, 3], the second element is [4, 5, 6] and last
element is [7, 8, 9].
We can access the elements of a nested list using multiple indices. For
example,
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(my_list[0][0]) #1
print(my_list[1][2]) #6
print(my_list[2]) # [7, 8, 9]
DICTIONARIES
• Creating Dictionaries;
• Operations on Dictionaries;
• Built-in Functions on Dictionaries;
• Dictionary Methods;
• Populating and Traversing Dictionaries.
DICTIONARIES
• Creating dictionaries:

Ex1: dict = {1: ‘C', 2: ‘C++', 3: ‘Python'}


print(dict)
Output: {1: 'C', 2: 'C++', 3: 'Python'}

Ex2: dict1 = { "brand": "Ford", "model": "Mustang", "year": 1964 }


print(dict1)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items - Data Types
• The values in dictionary items can be of any data type.
• Example: String, int, boolean, and list data types:

Ex1: dict1 = {“brand”: ‘Ford',


“Model”: ‘Mustang',
“year”: 1964,
“colors”: [“red”, “white”, “blue”]}
print(dict)
Operations on Dictionaries

Accessing Dictionary Values


• A value is retrieved from a dictionary by specifying its corresponding key
in square brackets; dictionary_name[“key”]
• If you refer to a key that is not in the dictionary, Python raises an
exception: KeyError.
Example :
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}

print(“Printing Employee Data .... ")

print("Dictionary is", Employee)

print("Name of the employee is", Employee["Name"])

print("Age:", Employee["Age"])

print("Salary:", Employee["salary"])

print("Company:", Employee["Company"])
1. # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

2. # Adding elements to dictionary one at a time


Dict[1] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("Dictionary after adding 3 elements: ")
print(Dict)
3. # Adding set of values with a single key.
The emp_ages doesn’t exist to dictionary.

Dict[“emp_ages”] = [20, 33, 30]


print(Dict)

4. # Updating existing key’s value.

Dict[3] = ‘Rocky'
print("Dictionary after updating: ")
print(Dict)
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to dictionary one at a time


Dict[1] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("Dictionary after adding 3 elements: ")
print(Dict)

Dict[“emp_ages”] = [20, 33, 30]


print(Dict)

# Updating existing key’s value.


Dict[3] = ‘Rocky'
print("Dictionary after updating: ")
print(Dict)
Removing elements from Dictionary
• We use del statement to remove/delete an element from the dictionary.
• For example,

Employee = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


del Employee["Name"]
print(Employee)

del Employee
print(Employee)
Checking for existence of keys in Dictionary
• We use in keyword check existence of key in the dictionary.
• For example,

Employee = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print(“Name” in Employee)

del Employee["Name"]
print(“Name” in Employee)
Looping over keys or values in dictionary
• We can loop through in dictionary for keys or values.
• For example,

Employee = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


for key in Employee:
print(key)

for value in Employee.values():


print(vale)
Built-in Functions on Dictionaries
1. len()

2. keys()

3. values()

4. items()

5. get()

6. pop()

7. sorted()
Dictionary Methods
1. clear()

2. copy()

3. update()

4. pop()

5. popitem()

6. get()

7. items()

8. keys()
Dictionary Methods
1. clear() : It removes all the key-value pairs from the dictionary.

Emp = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


Emp.clear()
print(Emp)

print(Emp.clear())

#{}

# None
Dictionary Methods
2. copy() : It returns a shallow copy of the dictionary.

Emp = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


New_Emp = Emp.copy()
print(New_Emp)

# {'Name': 'Dev', 'Age': 20, 'Salary': 45000, 'Company': 'WIPRO'}


Dictionary Methods
3. update() : It adds the key-value pairs from one dictionary to another. If a key
already exists in the dictionary, then its value is updated.

Emp1 = {"Name": "Dev", "Age": 20}


Emp2 = {“Salary":45000, "Company":"WIPRO"}

Emp1.update(Emp2)

print(Emp1)

# {'Name': 'Dev', 'Age': 20, 'Salary': 45000, 'Company': 'WIPRO'}


Dictionary Methods
4. pop() : It removes the key-value pair associated with the specified key and
returns the value.

Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print(Emp1.pop(“Salary”))

print(Emp1)

# 45000
# {'Name': 'Dev', 'Age': 20, 'Company': 'WIPRO'}
Dictionary Methods
5. popitem() : It removes the item (key-value pair) inserted into the dictionary.
The removed item is the return value of the popitem() method, as a tuple.
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print(Emp1.popitem())

print(Emp1)

# ('Company', 'WIPRO')
# {'Name': 'Dev', 'Age': 20, 'Salary': 45000}
Dictionary Methods
6. get() : It returns the value of the specified key. If the key does not exist, it
returns the specified default value (None).
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print(Emp1.get(“Age”))

# 20
Dictionary Methods
7. items() : It returns a list of all the key-value pairs in a dictionary as tuples.

Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print(Emp1.items())

# dict_items([('Name', 'Dev'), ('Age', 20), ('Salary', 45000), ('Company', 'WIPRO')])


Dictionary Methods
8. keys() : It returns a list of all the key in a dictionary.

Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}


print(Emp1.keys())

# dict_keys(['Name', 'Age', 'Salary', 'Company'])


Built-in Functions / Dictionary Methods
1. len() 7. sorted()
2. keys() 8. clear()
3. values() 9. copy()
4. items() 10. update()
5. get() 11. popitem()
6. pop()
Populating and Traversing(Iterating) Dictionaries
• Populating a dictionary in Python is simply a matter of assigning values to
keys using the key-value syntax. Here’s an example of creating a dictionary
with some data;
• dict1 = {
"Name": "Dev",
"Age": 20,
“Salary":45000,
"Company":"WIPRO“
}
Populating and Traversing(Iterating) Dictionaries
• To Traverse or to Iterate over a dictionary in Python is, to use a for loop.
There are several ways to iterate over the keys, values or items (key-value) of
a dictionary in Python. Example;

• Iterating over keys,


• Iterating over values, and
• Iterating over items.
Employee = {"Name": "Dev", "Age": 20, "salary":45000, "Company":"WIPRO"}
#Iterating over keys,
for key in Employee:
print(key)
#Iterating over values,
for value in Employee.values():
print(value)
#Iterating over items
for key, value in Employee.items():
print(key, value)
#Iterating/Traversing: Python program example;
Employee = {"Name": "Dev", "Age": 20, "salary":45000, "Company":"WIPRO"}

for i in Employee:
print(i)
for i in Employee:
print(Employee[i])

for i in Employee.keys():
print(i)
for i in Employee.values():
print(i)

print(Employee.keys())
print(Employee.values())
TUPLES
• Creating Tuples;
• Operations on Tuples;
• Built-in Functions on Tuples;
• Tuple Methods.
Tuples
• A Tuple is an ordered collection of elements, similar to a list. However tuples
are immutable, meaning that their values cannot be changed once they are
created.
• Tuple elements are enclosed within parentheses and separated by commas.

• A tuple in Python is similar to a list. The difference between the two is that
we cannot change the elements of a tuple once it is assigned whereas we
can change the elements of a list.
Creating a Tuple
• A Tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.

• A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).

• Syntax : tuple_name = (value1, value2, value3, ………………….)


Creating a Tuple: Different types of tuples
# Empty tuple # tuple with mixed datatypes
my_tuple = () my_tuple = (1, "Hello", 3.4)
print(my_tuple) print(my_tuple)

# Tuple having integers # nested tuple


my_tuple = (1, 2, 3) my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple) print(my_tuple)
Create a Python Tuple With one Element
• In Python, creating a tuple with one element is a bit tricky. Having one
element within parentheses is not enough.
• We will need a trailing comma to indicate that it is a tuple,
• var1 = ("hello")

var1 = ("Hello") # string • print(type(var1)) # <class 'str'>


• # Creating a tuple having one element
var2 = ("Hello",) # tuple
• var2 = ("hello",)
• print(type(var2)) # <class 'tuple'>
• # Parentheses is optional
• var3 = "hello",
• print(type(var3)) # <class 'tuple'>
Operations on Tuples
• Indexing, Slicing, Concatenation, Repetition, Length, Membership test,
Iteration.
1. Indexing: We can use the index operator [ ] to access an item in a tuple,
where the index starts from 0.
• Example: my_tuple = (1, 2, ‘a’, ‘b’, ‘c’)
print(my_tuple[2])

# prints - a
Operations on Tuples
2. Negative Indexing: Python allows negative indexing for its sequences. The
index of -1 refers to the last item, -2 to the second last item and so on. For
example;

# accessing tuple elements using negative indexing


letters = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')

print(letters[-1]) # prints ‘n'


print(letters[-6:-2]) # prints ('p', ‘y', ‘t', ‘h‘)
Operations on Tuples
3. Slicing: We can access a range of items in a tuple by using the slicing operator
colon :
my_tuple = ('p', ‘y', ‘t', ‘h', ‘o', ‘n', ‘p', ‘r', ‘o‘, ‘g’, ‘r’, ‘a’, ‘m’)

# elements 2nd to 4th index


print(my_tuple[1:4]) ('y', 't', 'h')

# elements beginning to some element


print(my_tuple[:-7]) ('p', 'y', 't', 'h', 'o', 'n')

# elements 8th to end


print(my_tuple[7:]) ('r', 'o', 'g', 'r', 'a', 'm')

# elements beginning to end


print(my_tuple[:]) ('p', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'o', 'g', 'r', 'a', 'm')
Operations on Tuples
4. Concatenation: We can concatenate two tuples using + operator. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
letters2 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
letters3 = letters1 + letters2
print(letters3)
# ('p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n')
Operations on Tuples
5. Repetition: We can repeat a tuple using the * operator. For example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
letters2 = letters1 * 3
print(letters2)
# ('p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n')

6. Length: We can find the length of a tuple using the len() function. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print(len(letters1))
#6
Operations on Tuples
7. Membership test: We can check if an element is present in a tuple using the
in operator. For example;
my_tuple = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print( ‘p’ in my_tuple) #True
print( ‘g’ in my_tuple) #False
8. Iteration: We can iterate over the elements of a tuple using a for loop. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
p
for elements in letters1: y
t
print(elements) h
o
n
Built-in Functions on Tuples
• len()
• max()
• min()
• sum()
• sorted()
Built-in Functions on Tuples
• len() – returns the number of elements in a tuple.

• max() – returns the largest element in a tuple.

• min() – returns the smallest element in a tuple.

• sum() – returns the sum of all the elements from a


tuple. (only numeric)

• sorted() – returns a sorted list of element in a tuple.


Built-in Functions on Tuples: Example
my_tuple = (4, 5, 6, 1, 2, 3)

print(len(my_tuple)) #6

print(max(my_tuple)) #6

print(min(my_tuple)) #1

print(sum(my_tuple)) # 21

print(sorted(my_tuple)) # [1, 2, 3, 4, 5, 6]
Tuple Methods
• Tuples are immutable in Python, which means they cannot be modified once
they are created. As a result, there are only two methods defined for tuples;
1. count()
2. index()
• 1. count(): This method takes one argument and returns the number of
times that argument appears in the tuple:
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(count(1))
#4
Tuple Methods
• 2. index(): This method takes one argument and returns the index of the
first occurrence of that argument in the tuple. If the argument is not found,
it raises ValueError.
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(index(4)) #3
print(my_tulpe(index(1)) #0

Note: These methods do not modify the original tuple. If you wish to modify a
tuple, you must first convert it to a list, make changes and then convert it back
to a tuple.
SETS
• Creating Sets;
• Operations on Sets;
• Built-in Functions on Sets;
• Set Methods.
Sets
• A set is an unordered collection of unique elements. In other words, Python
Set is a collection of elements (objects) that contains no duplicate elements.
• Sets are enclosed in curly braces { }.
• The set data type is mutable, which means we can add or remove elements
from it.
• A set is a collection which is unordered, unchangeable, and unindexed.
• Sets are unordered, i.e we cannot access elements by index value
(unindexed). Instead, we can iterate over the set using a loop or we can use
the in operator to check if an element is present in the set.
• Set items are unchangeable, but you can remove items and add new items.
• Sets do not allow duplicate elements. If you try to add a duplicate element to
a set, it will be ignored.
Creating Sets
• In Python, we create sets by placing all the elements inside curly braces {},
separated by comma and also set can be created using the set() function.
• A set can have any number of items and they may be of different types
(integer, float, tuple, string etc.). But a set cannot have mutable elements like
lists, sets or dictionaries as its elements.
Creating Sets: Example
#1 create a set of integer type
• student_id = {112, 114, 116, 118, 115}
• print('Student ID:', student_id)
Note:
#2 create a set of string type When you run this code, you might
get output in a different order.
• vowel_letters = {'a', 'e', 'i', 'o', 'u'} This is because the set has no
particular order.
• print('Vowel Letters:', vowel_letters)

#3 create a set of mixed data types


• mixed_set = {'Hello', 101, -2, 'Bye'}
• print('Set of mixed data types:', mixed_set)
Creating Sets: Example
• empty1 = set() # create an empty set

• empty2 = { } # create an empty dictionary

• print('Data type of empty1:', type(empty1)) # check data type of empty1

• print('Data type of empty2', type(empty2)) # check data type of empty2

Data type of empty1: <class 'set'>


Data type of empty2: <class 'dict'>
Creating Sets: Example
thisset = set(["apple", "banana", "cherry"])
print(thisset)
print(type(thisset))

# Note: the set list is unordered, so the result will display the items in a random
order.

# {'cherry', 'banana', 'apple'}


# <class 'set'>
Operations on Sets
• Python Set provides different built-in methods to perform mathematical set
operations like union |, intersection &, subtraction (difference) -, symmetric
difference ^ and membership test (in).
1. Union |: The union of two sets contains all the elements that are in either set.
We can use | operator or union() method to perform this operation.
Example:
A = {1, 3, 5} # first set
B = {0, 2, 4} # second set
print('Union using |:', A | B) # perform union operation using |
print('Union using union():', A.union(B)) # perform union operation using union()
Operations on Sets
2. Intersection &: The intersection of two sets contains only the elements that
are in common to both sets. We can use & operator or intersection() method to
perform this operation.
Example:
A = {1, 3, 5} # first set
B = {1, 2, 3} # second set
print(A & B) # perform intersection using &
print(A.intersection(B)) # perform intersection using intersection()
Operations on Sets
3. Difference between two sets - : The difference between two sets contains only
the elements that are in first set but not in the second set. We can use the –
operator or the difference() method to perform this operation.
Example:
A = {2, 3, 5} # first set
B = {1, 2, 6} # second set
print(A - B) # perform difference op. using -
print(A.difference(B)) # perform difference op. using difference()
Operations on Sets
4. Set Symmetric Difference ^ : The symmetric difference between two sets
contains all elements of two sets without the common elements. We can use the
^ operator or symmetric_difference() method to perform this.
Example:
A = {2, 3, 5} # first set
B = {1, 2, 6} # second set
print(A ^ B)
print(A.symmetric_difference(B))
Operations on Sets
5. Membership Test in : We can test if an element is a member of a set using the
in operator.
Example:
A = {2, 3, 5}
print(2 in A) #True
print(4 in A) #False
Built-in Functions on Sets
• len()
• max()
• min()
• sum()
• sorted()
• enumerate()
Built-in Functions on Sets
• len(): The len() function returns the number of items in an object.
• Example:
languages = {'Python', 'Java', 'JavaScript‘}
length = len(languages)
print(length)

# Output: 3
Built-in Functions on Sets
• max(): The max() function returns the largest item in an iterable. It can also
be used to find the largest item between 2 or more parameters.
• Example:
numbers = {9, 34, 11, -4, 27}
max_number = max(numbers)
print(max_number)

# Output: 34
Built-in Functions on Sets
• min(): The min() function returns the smallest item in an iterable. It can also
be used to find the smallest item between 2 or more parameters.
• Example:
numbers = {9, 34, 11, -4, 27}
min_number = min(numbers)
print(min_number)

# Output: -4
Built-in Functions on Sets
• sum(): The sum() function adds the items of an iterable and returns the sum.
• Example:
marks = {65, 71, 68, 74, 61}
total_marks = sum(marks)
print(total_marks)

# Output: 339
Built-in Functions on Sets
• sorted(): The sorted() function sorts the elements of a given iterable in a
specific order (ascending or descending) and returns it as a list.
• Example:
numbers = {65, 71, 68, 74, 61}
sorted_nos = sorted(numbers) reverse=True

print(sorted_nos)

# Output: [61, 65, 68, 71, 74]


Built-in Functions on Sets
• enumerate(): The enumerate() function returns an enumerate object. It
contains the index and value for all the items of the set as a pair..
• Example:
languages = {'Python', 'Java', 'JavaScript‘}
enumerate_prime = enumerate(languages)

# convert enumerate object to list


print(list(enumerate_prime))

# Output: [(0, 'Python'), (1, 'Java'), (2, 'JavaScript')]


Set Methods
1. add() method: adds a given element to a set. If the element is already present,
it doesn't add any element.
• Example:
prime_numbers = {2, 3, 5, 7}
prime_numbers.add(11)
print(prime_numbers) # Output: {2, 3, 5, 7, 11}

2. clear() method: removes all the items from the list.


prime_numbers = {2, 3, 5, 7}
prime_numbers.clear()
print(prime_numbers) # Output: set( )
3. copy() method: returns a copy of the set.
• Example:
numbers = {1, 2, 3, 4, 5}
new_numbers = numbers.copy()
print(new_numbers) # Output: {1, 2, 3, 4, 5}

4. difference() method: computes the difference of two sets and returns items
that are unique to the first set.
numbers1 = {1, 3, 5, 7, 9}
numbers2 = {2, 3, 5, 7, 11}
print(numbers.difference(numbers2)) # Output: {1, 9}
5. difference_update() method: computes the difference between two sets (A -
B) and updates set A with the resulting set.
• Example:
nos1 = {1, 3, 5, 7, 9}
nos2 = {2, 3, 5, 7, 11}
nos1.difference_update(nos2)
print(nos1) # Output: {1, 9}
6. pop () method: randomly removes an item from a set and returns the
removed item.
• Example:
A = {‘a’, ‘b’, ‘c’, ‘d’}
removed_item = A.pop()
print(removed_item) # Output: c or d or any1
7. discard() method: Removes an element from the set if it is a member. (Do
nothing if the element is not in set.)
numbers = {2, 3, 4, 5}
numbers.discard(3)
print(numbers) # Output: {2, 4, 5}

8. remove() method: Removes the specified element from the set.


languages = {'Python', 'Java', 'English'}
languages.remove(‘English’)
print(languages) # Output: {‘Python’, ‘Java’}
LISTS DICTIONARIES TUPLES SETS

• [ ….. ] • { ….. } • ( ….. ) • { ….. }


• Allows • No duplicate • Allows • No duplicate
duplicate elements. duplicate elements.
elements. elements.
• Changeable • Changeable • Unchangeable • Cannot be
(Mutable) (Mutable) (Immutable) changed, but
can be added,
non-indexed.
• Ordered. • Ordered. • Ordered. (Mutable)
• Unordered.
LISTS DICTIONARIES TUPLES SETS

• Creating Lists; • Creating • Creating • Creating Sets;


• Operations on Dictionaries;
Tuples; • Operations on
Lists; • Operations on
• Built-in Dictionaries; • Operations on Sets;
Functions on • Built-in Tuples; • Built-in
Lists; Functions on
• Implementation Dictionaries; • Built-in Functions on
of Stacks and • Dictionary Functions on Sets;
Queues using Methods; Tuples;
Lists; • Set Methods.
• Populating and • Tuple
• Nested Lists. Traversing
Dictionaries. Methods.

You might also like