0% found this document useful (0 votes)
5 views34 pages

UNIT-2 Python Programming

Uploaded by

trnandan41
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)
5 views34 pages

UNIT-2 Python Programming

Uploaded by

trnandan41
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

UNIT-2 Python Programming.

List: A list is an ordered collection of values of any data type that can be stored
in a single variable.
Example:
# Creating a list of fruits
fruits = ["apple", "banana", "cherry"]
print(fruits)

Nested List: A nested list in Python is a list that contains other lists as its
elements. This allows you to create multi-dimensional data structures, such as
matrices or tables.
Example:
# Basic nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list)

Traversing a list: we can use for loop to traverse all the element in list in
sequential order.
Example:
fruits = ["apple", "banana", "cherry"]
for i in fruits:
print(fruits[i])
Indexing in List: Indexing in Python lists allows you to access individual
elements by their position.
Example:
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry

Slicing: we can access a range of elements using slicing.


The syntax is list[start:stop:step].
Example:
fruits = ["apple", "banana", "cherry"]
# Slicing examples
print(fruits[0:2]) # Output: ['apple', 'banana']
print(fruits[1:]) # Output: ['banana', 'cherry']
print(fruits[:2]) # Output: ['apple', 'banana']
print(fruits[::2]) # Output: ['apple', 'cherry']
Negative Slicing:
Print(fruits[-1:-4])
Print(fruits[-1:-3])
List are mutable: lists in Python are mutable, which means you can change
their content without changing their identity. This includes adding, removing,
or modifying elements.
Example:
# Modifying an element
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']

Basic List operations:


Concatenate: The concatenate operation merges two lists and returns a single
list. The concatenation is performed using the + sign.
Example:
L1 = [1, 2, 3]
L2 = [4, 5 ,6]
print(L1+L2)
Repetition of List: python allows us to repeat or replicate the elements of the
list using repetition operator which is denoted by symbol *.
Example:
L1 = [1, 2, 3]
Print(L1*2)
Membership operators (in and not in): The in operator is a type of
membership operator. It is used to check if a particular element is present in
the list or not.
Example:
L1 = [1, 2, 3]
Print(2 in L1)
The not in operator is also a type of membership operator. It is used to check if
a particular element is not present in the list.
Example:
L1 = [1, 2, 3]
Print(2 not in L1)
Comparing List: A comparison operator in python, also called python relational
operator(<, >, <=, >=, ==, != )that compare the values of two operands and
returns true or false based on whether the condition is met.
Less than (<): it checks if the left value of list is lesser than that on the right list.
Example:
L1 = [1, 2, 3]
L2 = [4, 5 ,6]
Print(L1<L2)
Greater than (>): it checks whether the left value of list is greater than that on
the right list.
Example:
L1 = [1, 2, 3]
L2 = [4, 5 ,6]
Print(L1>L2)
Less than or equal to (<=) operator: this operator return true only if the value
on the left is either less than or equal to that on the right of the list.
Example:
L1 = [1, 2, 3]
L2 = [4, 5 ,6]
Print(L1<=L2)
Greater than or equal to(>=) operator: this operator return true only if the
value on the left is greater than or equal to that on the right of the list.
Example:
L1 = [1, 2, 3]
L2 = [4, 5 ,6]
Print(L1<=L2)
Equal to (==) operator: it returns true if the values on either side of the list are
equal.
Example:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # True
Not Equal to (!=) operator: it true if the value on either side of the list are not
equal.
Example:
list1 = [1, 2, 3]
list2 = [3, 2, 1]
print(list1 != list2) # True
Copying List: Copying list can be done different ways those are:
Using the copy() method: copy() method copies the list and returns the copied
list
Example:
original_list = [1, 2, 3]
copied_list = original_list.copy()
Using List Slicing: We can slice our original list and store it into a new variable
as follows.
Example:
original_list = [1, 2, 3]
copied_list = original_list[:]
Using the list() Function: We can copy lists using the built in function list() as
follows:
Example:
original_list = [1, 2, 3]
copied_list = list(original_list)
Using assignment operator(=): The simplest way to make a copy of the list is to
assign a list to another list using an assignment operator(=).
Example:
L1 = [10,20,30]
L2 = L1
print(L2)
Nested List: The nested list are just lists within lists.
Example:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Access nested list items by index:
print(nested_list[0][1]) # Outputs: 2
Traversing nested list using for-loop.
for row in nested_list:
for col in row:
print(item)
Bulit-in Function used on list:
1. len(): Gets the length of the list.
Example:
len([1, 2, 3]) # Outputs: 3
2. max(): Returns the largest item.
Example:
max([1, 2, 3]) # Outputs: 3
3. min(): Returns the smallest item.
Example:
min([1, 2, 3]) # Outputs: 1
4. sum(): Returns the sum of the elements.
Example:
sum([1, 2, 3]) # Outputs: 6
5. sorted(): Returns a sorted copy of the list.
Example:
sorted([3, 1, 2]) # Outputs: [1, 2, 3]

List Methods:
1. append(x): Adds an item to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.append(4)
2. insert(i, x): Inserts an item at a given position.
Example:
my_list.insert(1, 'a') # List is now [1, 'a', 2, 3, 4, 5, 6]
3. remove(): this method searches for the given element in the list and
removes the first matching element.]
Example:
my_list.remove('a')
4. extend(): This method used to add contents of list2 to the end of list1
Example:
L1 = [10,20]
my_list.extend(L1)
Print(my_list)
5. pop(): Removes and returns the item at the given position in the list.
Example:
L1 = [10,20,30,40,50]
[Link](2)
print(L1)
6. clear(): Removes all items from the list.
Example:
[Link]()
7. count(): Returns the number of times the specified
element appears in the list.
Example:
my_list = [2,1,6,2,10]
my_list.count(2) # Outputs: 2
8. sort(): Sorts the items of the list in place.
Example:
my_list.sort()
my_list.sort(reverse=True)
9. reverse(): Reverses the elements of the list in place.
Example:
my_list.reverse()
10. index(): The index() method searches for the given element from the start
of the list and returns its index.
Example:
my_list = [1, 2, 3, 2]
my_list.index(2) # Outputs: 1

Dictionaries in python:
Dictionary is a mutable unordered collection of elements in the form of a
key:value pairs that associate keys to values, with the requirement that the key
are unique within a dictionary.
Example:
my_dict = {"name": "Tom", "age": 30, "city": "New York"}
Creating dictionary:
Python offers several ways to create dictionaries.
There are two main ways are:
1. Creating Dictionary by using Curly Braces{}.
2. Creating Dictionary by using dict() function.

Creating Dictionary by using Curly Braces{}: to create a dictionary, the items


entered are separated by commas and enclosed in curly braces. Each items is a
key value pair, separated through colon(:).
Example:
my_dict = {"name": "Tom", "age": 30, "city": "New York"}
Creating Dictionary by using dict() function: the python dict() is built in
function that returns a dictionary object or simply creates a dictionary in
python
By using dict() function we can create dictionary three ways:
1. Creating dictionary using dict(** kwargs):
Kwarg: it’s a keyword argument and is optional in function. If no keyword
arguments are passed, then it create empty dictionary.
Example: my_dictionary = dict(a=10,b=20,c=30)
Print(my_dictionary)

2. Creating dictionary using dict(mapping,**kwargs)


Mapping is a dictionary object. It is also optional. we can pass a dictionary as
well as keyword arguments to the dict() function
Example:
original_dict = {'name': 'John', 'age': 30}
new_dict = dict(original_dict)
original_dict = {'city': 'New York'}
new_dict = dict(original_dict, name='John', age=30)

3. Creating dictionary using dict(iterable,**kwargs)


An iterable is the collection of key-value pairs where keys must be unique and
immutable. An iterable object could be a tuple, list, set. It is also optional. We
can pass a iterable object as well as keyword argument to the dict() function.
Example:
key_value_pairs = [('name', 'John'), ('age', 30)]
my_dict = dict(key_value_pairs)
key_value_pairs = [('city', 'New York')]
my_dict = dict(key_value_pairs, name='John', age=30)
Accessing Key Value pair in a Dictionary:
In Dictionary individual key:value pair in a dictionary can be accessed through
keys by specifying it inside square brackets. The key provided within the square
brackets indicates the key:value pair being accessed.
Example:
Student = {1001: “Asha”, 1002: “Nirmala”, 1003: “Mary”}
print(Student[1002])

Traversing Dictionary: a dictionary is iterable and this means that we can


traverse or iterate all the items in dictionary.
There are mainly four ways to iterate over the dictionary in python:
1. Iterating through keys directly.
The simplest way to iterate a dictionary through keys directly by using for loop.
Once we get key, then we can access its value.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict:
print(key, ‘->’, my_dict[key])
2. Iterating using keys():
The keys() method extract the keys of the dictionary and returns the list of keys
as a view object. The returned view object is iterable and hence we can iterate
the dictionary using loop.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict.keys():
print(key)
3. Iterating using values():
The value() method extracts the values of the dictionary and returns the list of
values as a view object. The returned view object is iterable and hence we can
iterate the dictionary using loop.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for value in my_dict.values():
print(value)

4. Iterating using items(): the items() method returns a view object that
display a list of dictionary’s (key,value) tuple pairs. The [Link]()
converts each key-value pair in a dictionary into a tuple.
Example:
Employee = {‘name’: ‘Ram’, ‘age’ : 25, ‘Course’ : ‘BCA’}
Dict_item = [Link]()
print(Dict_item)

Membership Operators( in and not in):


The in operator is a type of membership operator. It is used to check if a
particular key is present in the dictionary or not.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
if 'name' in my_dict:
print("Key 'name' is present in the dictionary.")
Using not in to Check Non-Membership:
The not in operator is a type of membership operator.
This checks if a specified key does not exist in the dictionary.
Example:
if 'salary' not in my_dict:
print("Key 'salary' is not present in the dictionary.")

Comparing Dictionaries.
We can use the == and != operators to test whether two dictionaries contain
the same items.
Using == Operator: Checks if dictionaries have the same key-value pairs
Example:
dict1 = {'name': 'John', 'age': 30}
dict2 = {'name': 'John', 'age': 30}
print(dict1 == dict2) # True
Using != Operator: Checks if dictionaries are different.
Example:
dict1 = {'name': 'John', 'age': 30}
dict2 = {'name': 'Jane', 'age': 25}
print(dict1 != dict2) # True
Built-in functions used on dictionaries:
There are many built in functions for which a dictionary can be passed as an
argument.
• len(): Returns the number of items in the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
print(len(my_dict))
• any(): It returns True if any of the elements in the iterable (in this case,
the dictionary) are true. If the dictionary is empty or all elements are
false, it returns False.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(any(my_dict))
• all(): The all() function returns Boolean true value if all the keys in the
dictionary are true else return false.
Example:
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(all(my_dict))
• Sorted(): The sorted() function is great for sorting dictionaries by keys
or Values.
Example:
my_dict = {'b': 2, 'c': 3, 'a': 1}
sorted_by_keys = dict(sorted(my_dict.items()))
print(sorted_by_keys)

Dictionary Methods: python provides very use full built-in list methods to work
with dictionary.
• clear(): Removes all items from the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
my_dict.clear()
print(my_dict)
• copy(): Returns a shallow copy of the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
my_copy = my_dict.copy()
• get(): Returns the value for a specified key if the key is in the dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
value = my_dict.get('name')
• items(): Returns a view object that displays a list of a dictionary's key-
value tuple pairs.
Example:
my_dict = {'name': 'John', 'age': 30}
items = my_dict.items()
print(items)
• keys(): Returns a view object that displays a list of all the keys in the
dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
keys = my_dict.keys()
• pop(): Removes and returns the value for a specified key.
Example:
my_dict = {'name': 'John', 'age': 30}
age = my_dict.pop('age')
print(age)
• popitem(): Removes and returns the last key-value pair as a tuple.
Example:
my_dict = {'name': 'John'}
item = my_dict.popitem()
print(item)
• setdefault(): Returns the value of a key if it exists; otherwise, inserts the
key with a specified value.
Example:
my_dict = {'name': 'John', 'age': 30}
age = my_dict.setdefault('age', 25)
print(my_dict)
• update(): Updates the dictionary with elements from another dictionary
or an iterable of key-value pairs.
Example:
my_dict = {'name': 'John', 'age': 30, ‘city’:‘Bangalore’}
my_dict.update({'city': 'New York', 'age': 31})
print(my_dict)
• values(): Returns a view object that displays a list of all the values in the
dictionary.
Example:
my_dict = {'name': 'John', 'age': 30}
values = my_dict.values()
The del statement: The Del keyword is used to delete objects. In python,
everything is an object, so the del keyword can also be used to delete all the
key value pairs in dictionary or a specific item in dictionary.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
del my_dict['age']
print(my_dict)

Tuple in python:
Tuple is a one of the built in data type in python. A tuple is a sequence or
ordered collection of elements of different data types.
Tuple are immutable, tuple allows duplicate values.
Example: my_tuple = (1, 2, 3)
Creating Tuples:
Creating empty tuple
Example:
A = ()
print(A)
Creating Mixed Data type tuple:
Example:
A = (‘Anu’, ‘F’, 21, 92.36)
print(A)
Creating Nested Tuple:
Example:
A = (74, 92,45, (35,85), 56,27)
print(A)
Creating tuple using Tuple() function:
Example:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Outputs: (1, 2, 3)
Tuples are Immutable:
Tuples in Python are immutable, meaning once they are created,
their elements cannot be changed, added, or removed.
Example:
my_tuple = (1, 2, 3)
This will raise an error:
my_tuple[0] = 4 # TypeError: 'tuple' object does not support item assignment
Indexing in tuple:
Each individual element in a tuple can be accessed using a technique called
indexing.
Example: positive indexing in tuple.
my_tuple = (10, 20, 30, 40)
print(my_tuple[0]) # Outputs: 10
print(my_tuple[2]) # Outputs: 30

Example: negative indexing in tuple.


print(my_tuple[-1]) # Outputs: 40
print(my_tuple[-2]) # Outputs: 30
Indexing with Ranges (Slicing):
Example:
print(my_tuple[1:3]) # Outputs: (20, 30)
print(my_tuple[:2]) # Outputs: (10, 20)
print(my_tuple[2:]) # Outputs: (30, 40)

Step Indexing:
• Allows skipping elements.
Example:
print(my_tuple[::2])
print(my_tuple[::-1])

Slicing in Tuple:
Slicing in tuples allows you to access a specific subset of elements from a tuple.
Example: Positive Slicing in tuple.
my_tuple = (10, 20, 30, 40, 50)
sliced_tuple = my_tuple[1:4]
print(sliced_tuple) # Outputs: (20, 30, 40)
Example: Negative Slicing in tuple.
print(my_tuple[-4:-1]) # Outputs: (20, 30, 40)
Example: Positive and negative Slicing in tuple with Step count
print(my_tuple[::2]) # Outputs: (10, 30, 50)
print(my_tuple[::-1]) # Outputs: (50, 40, 30, 20, 10)
Basic Tuple Operations:
Python allows certain operations on tuple data type such as concatenation,
repetition, membership and comparing.
• Concatenation: Concatenating two tuples means joining two tuples.
Example:
my_tuple = (1,2,3,4)
combined_tuple = my_tuple + (6, 7, 8)
print(combined_tuple) # Outputs: (1, 2, 3, 4, 5, 6, 7, 8)
• Repetition: Python allows us to repeat or replicate the elements of the
tuple using repetition operator which is denoted by symbol *.
Example:
my_tuple = (1,2,3,4)
repeated_tuple = my_tuple * 2
print(repeated_tuple)
• Membership operators (in and not in):
The in operator is a type of membership operator. It is used to check if a
particular element is present in the tuple or not.
The not in operator is a type of membership operator. It is used to check if a
particular element is not present in the tuple.
Example:
print(3 in my_tuple) # Outputs: True
print(6 not in my_tuple) # Outputs: True
• Comparing tuple:
A comparison operator in python, also called python relation operator(<, >, <=,
>=, ==, !=) that compare the values of two operands and returns true or false
based on whether the condition is met.
Example:
A = (10,20,30,40,50)
B = (60,70,80,90,100)
Print(A==B)
Print(A!=B)
Print(A>B)
Print(A<B)
Print(A<=B)
Print(A>=B)
• Copying Tuple: The simplest way to make a copy of the tuple is to assign
a tuple using an assignment operator(=).
Example:
original_tuple = (1, 2, 3)
copied_tuple = original_tuple
print(copied_tuple) # Outputs: (1, 2, 3)
Nested tuple: Nested tuples are tuples within tuples.
They allow you to create complex data structures by nesting one tuple inside
another.
Example:
nested_tuple = (1, (2, 3), (4, (5, 6)))
print(nested_tuple)
Accessing element of nested tuple in index:
Accessing the outer elements:
Example:
print(nested_tuple[0]) # Outputs: 1
print(nested_tuple[1]) # Outputs: (2, 3)
Accessing the inner elements:
Example:
print(nested_tuple[1][0]) # Outputs: 2
print(nested_tuple[2][1][1]) # Outputs: 6

Built-in Functions in used on tuple:


Tuples in Python come with several built-in functions that make them
powerful and convenient.
• len(): Returns the number of elements in the tuple.
Example:
my_tuple = (1, 2, 3)
print(len(my_tuple)) # Outputs: 3
• max(): Returns the largest element in the tuple.
Example:
my_tuple = (1, 2, 3)
print(max(my_tuple)) # Outputs: 3
• min(): Returns the smallest element in the tuple.
Example:
my_tuple = (1, 2, 3)
print(min(my_tuple)) # Outputs: 1
• sum(): Returns the sum of all elements in the tuple.
Example:
my_tuple = (1, 2, 3)
print(sum(my_tuple)) # Outputs: 6
• sorted(): Returns a sorted list of the tuple’s elements.
Example:
my_tuple = (3, 1, 2)
print(sorted(my_tuple)) # Outputs: [1, 2, 3]
• any(): Returns True if any element in the tuple is true.
Example:
my_tuple = (0, 1, 2)
print(any(my_tuple)) # Outputs: True
• all(): Returns True if all elements in the tuple are true.
Example:
my_tuple = (1, 2, 3)
print(all(my_tuple)) # Outputs: True

Using Zip() function in tuple: The Zip() method in python takes one or more
iterables (list, sets, string, etc) as arguments and merges each of them element
wise to create a single iterable.
Example:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
zipped = zip(tuple1, tuple2)
print(list(zipped)) # Outputs: [(1, 'a'), (2, 'b'), (3, 'c')]
Unzipping in tuple: There is no special function to unzip zipped iterables, we
can use the zip() method with the * operator to unzip a zip object.
Example:
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)
print(numbers) # Outputs: (1, 2, 3)
print(letters) # Outputs: ('a', 'b', 'c')

Tuple Packing and Unpacking:


Tuple Packing: This is the process of putting multiple values into a single tuple.
Example: # Packing values into a tuple
my_tuple = (“ANU” , “BCA”, 22)
print(my_tuple)
Tuple Unpacking: This is the process of extracting values from a tuple into
individual variables.
Example: # Unpacking values from a tuple
name, course, age = my_tuple
print(name)
print(course)
print(age)

Tuple Methods in python:


Tuples in Python are immutable, so they have fewer methods than lists.
• count(x): Returns the number of times x appears in the tuple.
Example:
my_tuple = (1, 2, 2, 3, 4)
print(my_tuple.count(2)) # Outputs: 2
• index(x): Returns the index of the first occurrence of x in the tuple.
Example:
my_tuple = (1, 2, 3, 4)
print(my_tuple.index(3)) # Outputs: 2

The del statement: The del keyword is used to delete objects. In python,
everything is an object, so the del keyword can also be used to delete all the
elements in a tuple.
Example:
my_tuple = (1, 2, 3, 4)
del my_tuple
# Now, my_tuple is undefined and trying to access it will raise an error
Example for Creating a New Tuple without an Element
my_tuple = (1, 2, 3, 4)
new_tuple = my_tuple[:1] + my_tuple[2:]
print(new_tuple) # Outputs: (1, 3, 4)

Converting tuple to list and list to tuple.


• The tuple can be converted to list using list() function by passing tuple as
argument.
• Once if is converted to the list, the contents in the list can be modified or
altered.
• Finally we can convert the update list into tuple by using tuple() function
by passing the updated list as an argument.
Example:
Converting a Tuple to a List
Use the list() function:
my_tuple = (1, 2, 3, 4)
my_list = list(my_tuple)
print(my_list) # Outputs: [1, 2, 3, 4]
Converting a List to a Tuple
Use the tuple() function:
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # Outputs: (1, 2, 3, 4)

Difference Between List and tuple

Sno LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is The implication of iterations is


2
Time-consuming comparatively Faster

The list is better for performing


A Tuple data type is appropriate
3 operations, such as insertion
for accessing the elements
and deletion.

Tuple consumes less memory as


4 Lists consume more memory
compared to the list
Sno LIST TUPLE

Tuple does not have many built-


5 Lists have several built-in methods
in methods.

Because tuples don’t change


Unexpected changes and errors are
6 they are far less error-
more likely to occur
prone.

Difference Between Tuple and Dictionary.

Tuple Dictionary

A tuple is a non-homogeneous data


Dictionary is a non-homogeneous
structure that can hold a single
data structure that contains key-
row as well as several rows and
value pairs.
columns.

Dictionaries are represented by


Tuples are represented by brackets ().
curly brackets {}.

Tuples are immutable i.e, we can not Dictionaries are mutable and keys
make changes. do not allow duplicates.

Dictionary is ordered (python 3.7


A tuple is ordered.
and above).

Tuple can be created using tuple() Dictionary can be created using the
function. dict() function.

Creating an empty Tuple: () Creating an empty dictionary: {}


Because the dictionary's entries are
As tuples are immutable, the reverse() in the form of key-value pairs,
method is not defined in them. the elements cannot be
reversed.

Example : {'companyname':
Example: ('Tutorialspoint', 'simple’,
'Tutorialspoint', 'tagline':
‘easy learning’)
'simplyeasylearning'}

Set in python:
A set in python is a unordered collection of unique elements. A Set is iterable,
mutable and doesn’t allow any type of duplicates as all the elements in set are
unique. Set is used to store multiple elements in a single variable.
Example: S1 = {2,4,6,8}
Creating Set: to create a set, place all elements or items separated by a comma
inside curly braces {}. The bulit-in set() function can also to create a set in
python.
Syntax: Set_name = {value 1,value 2,value 3………value n}
Syntax: Set_name = set()
Syntax: Set_name = set(sequence)
Example:
Intset = {2, 4, 6, 10}
Example:
Emptyset = set()
Example:
S1 = “Python”
Set1 = set(S1)
Traversing a Set: A set is iterable. This means that we can use a for loop to
traverse all the elements in the set.
Example:
S = {10, 20, 30, 40, 50}
For I in S:
Print(I)
Iterating Over two sets simultaneously using zip():
S1 = {10, 20, 30, 40, 50}
S2 = {60, 70, 80, 90, 100}
for (i1, i2) in zip(S1,S2):
Print(i1, i2)
Membership operator (in and not in):
The in operator is a type of membership operator. It is used to check if a
particular element is present in the set or not.
Example:
S1 = {10, 20, 30, 40, 50}
print( 10 in S1)
The not in operator is also a type of membership operator. It is used to check if
a particular element is not present in the set.
Example:
S1 = {10, 20, 30, 40, 50}
print(20 not in S1)
print(60 not in S1)
Comparing Sets: A comparison operator in python also called python relational
operator (<, >, ==,!=, >=, <=).
Equality (==): Check if two sets have the same elements.
Example:
set1 = {1, 2, 3}
set2 = {3, 2, 1}
print(set1 == set2) # Outputs: True
Inequality (!=): Check if two sets do not have the same elements.
Example:
set1 = {1, 2, 3}
set2 = {3, 2, 1}
print(set1 != set2) # Outputs: False
Subset (<= or <): Check if all elements of one set are in another.
Example:
set1 = {1, 2, 3}
subset = {1, 2}
print(subset <= set1) # Outputs: True (subset is a subset of set1)
print(subset < set1) # Outputs: True (subset is a proper subset of set1)
Superset (>= or >): Check if all elements of another set are in the first set.
Example:
superset = {1, 2, 3, 4}
print(superset >= set1) # Outputs: True (superset is a superset of set1)
print(superset > set1) # Outputs: True (superset is a proper superset of set1)
Built In functions used in Set:
len(): Returns the number of elements in the set.
Example:
my_set = {1, 2, 3, 4}
print(len(my_set)) # Outputs: 4
max(): Returns the maximum element in the set.
Example:
my_set = {1, 2, 3, 4}
print(max(my_set)) # Outputs: 4
min(): Returns the minimum element in the set.
Example:
my_set = {1, 2, 3, 4}
print(min(my_set)) # Outputs: 1
sum(): Returns the sum of all elements in the set.
Example:
my_set = {1, 2, 3, 4}
print(sum(my_set)) # Outputs: 10
sorted(): Returns a sorted list of the set's elements.
Example:
my_set = {1, 2, 3, 4}
print(sorted(my_set)) # Outputs: [1, 2, 3, 4]
all(): Returns True if all elements in the set are true.
Example:
my_set = {1, 2, 3}
print(all(my_set)) # Outputs: True
any(): Returns True if any element in the set is true.
Example:
my_set = {0, 2, 3}
print(any(my_set)) # Outputs: True
Set Methods: Python provides very useful built in list method to work with
sets. dir(set) is used to provide list all set methods in python.
• add(element): Adds an element to the set.
Example:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Outputs: {1, 2, 3, 4}
• update(iterable): Adds multiple elements to the set from another iterable.
Example:
my_set = {1, 2, 3, 4}
my_set.update([5, 6])
print(my_set) # Outputs: {1, 2, 3, 4, 5, 6}
• remove(element): Removes an element from the set. Raises a KeyError if
the element is not found.
Example:
my_set = {1, 2, 3, 4, 5, 6}
my_set.remove(3)
print(my_set) # Outputs: {1, 2, 4, 5, 6}
• discard(element): Removes an element from the set if it is present. Does no
thing if the element is not found.
Example:
my_set = {1, 2, 4, 5, 6}
my_set.discard(2)
print(my_set) # Outputs: {1, 4, 5, 6}
• pop(): pop method removes and returns a random element from the
set. Raises a KeyError if the set is empty.
Example:
my_set = {1, 4, 5, 6}
element = my_set.pop()
print(element)
• clear(): Removes all elements from the set.
Example:
my_set = {1, 4, 5, 6}
my_set.clear()
print(my_set) # Outputs: set()
• union(other_set): Returns a new set with all elements from both sets.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = [Link](set2)
print(union_set) # Outputs: {1, 2, 3, 4, 5}
• intersection(other_set): Returns a new set with elements common to
both sets.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = [Link](set2)
print(intersection_set) # Outputs: {3}
• difference(): Returns a new set with elements in the first set but not in the
second.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = [Link](set2)
print(difference_set)
• symmetric_difference(other_set): The symmetric_difference() method
return all the items present in given sets, except the items in their insertion.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Outputs: {1, 2, 4, 5}
• issubset(other_set): Checks if the set is a subset of another set.
Example:
set1 = {1, 2, 3}
myset = {1, 2}
print([Link](set1)) # Outputs: True
• isdisjoint(other_set): Checks if the set has no elements in common with
another set.
myset= {6, 7}
print([Link](myset)) # Outputs: True

You might also like