0% found this document useful (0 votes)
3 views25 pages

Python - Unit III

The document covers Python programming concepts related to strings, dictionaries, and sets, including string immutability, methods, and operations. It provides examples of string manipulation techniques such as indexing, slicing, concatenation, and case conversion, along with illustrative programs for practical understanding. Additionally, it includes algorithms for checking palindromes, counting vowels, and finding common characters in strings.

Uploaded by

Catherine J
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)
3 views25 pages

Python - Unit III

The document covers Python programming concepts related to strings, dictionaries, and sets, including string immutability, methods, and operations. It provides examples of string manipulation techniques such as indexing, slicing, concatenation, and case conversion, along with illustrative programs for practical understanding. Additionally, it includes algorithms for checking palindromes, counting vowels, and finding common characters in strings.

Uploaded by

Catherine J
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/ 25

UNIT III

STRINGS, DICTIONARY, SET

Strings: string slices, immutability, string functions and methods, string module. Dictionaries:
Operations (create, access, add, remove) and methods. (Insert, delete). Set operation (Access, Add,
Remove). Illustrative programs: creates a dictionary of radius of a circle and its circumference.

1. (i) Define methods in a string with an example program using at least 5 methods. (ii) How to
access characters of a string?

STRING

A string in Python is a sequence of characters enclosed in single quotes (' '), double quotes (" "), or
triple quotes (''' ''' or """ """). Strings are used to store and manipulate text.

✓ Immutable → Once created, strings cannot be modified.


✓ Indexed → Each character has an index, starting from 0.
✓ Slicing Supported → You can extract substrings using slicing.
Example:
# Single quotes
string1 = 'Hello, World!'

# Double quotes
string2 = "Python Programming"

# Triple quotes (used for multi-line strings)


string3 = '''This is a multi-line string'''

1. Indexing in Strings
• Definition: Accessing individual characters in a string using the subscript ([]) operator.
• Index: A position number assigned to each character in the string.
• Indexing Rules:
o The first character has index 0.
o The last character has index n-1 (where n is the length of the string).
o Negative indexing allows access from the end (-1 for the last character, -2 for second
last, etc.).
o Accessing an index beyond limits raises an error.
2. Traversing a String
• Definition: Accessing characters in a string one by one.
Indexing with while loop
text = "Python"
i = 0
while i < len(text):
print(text[i])
i += 1
Note : Python allows you to access spaces within a string using indexing because spaces are also treated as characters.

3. Concatenating, Appending, and Multiplying Strings


i. Concatenating Strings (+ Operator)
• Definition: Joining two or more strings together using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Adding a space between words

1
print(result) # Output: Hello World

ii. Appending Strings (+= Operator)


• Definition: Adding a string to an existing string using the += operator.
text = "Python"
text += " Programming"
print(text) # Output: Python Programming

iii. Multiplying Strings (* Operator)


• Definition: Repeating a string multiple times using the * operator.
text = "Hello "
print(text * 3) # Output: Hello Hello Hello

STRING METHODS

A string method is a built-in function in Python that allows us to manipulate and process string data
easily. These methods perform various operations such as case conversion, trimming spaces, replacing
substrings, and more.
1. Case Conversion Methods
Method Description Example
upper() Converts all characters to "hello".upper() → "HELLO"
uppercase.
lower() Converts all characters to lowercase. "HELLO".lower() → "hello"
title() Converts the first letter of each "hello world".title() → "Hello
word to uppercase. World"
capitalize() Converts the first letter of the string text = "python programming"
to uppercase. result = text.capitalize()
print(result)
O/p : Python programming
swapcase() Swaps uppercase to lowercase and "Python".swapcase() → "pYTHON"
vice versa.

2. String Modification Methods

Method Description Example


strip() Removes leading and " hello ".strip() → "hello"
trailing whitespace.
lstrip() Removes leading (left- " hello".lstrip() → "hello"
side) whitespace.
rstrip() Removes trailing (right- "hello ".rstrip() → "hello"
side) whitespace.
replace(old, Replaces occurrences of "hello world".replace("world",
new) a substring. "Python") → "hello Python"

2
3
(ii) How to access characters of a string?
1. Accessing Characters Using Indexing P
• In Python, strings are like arrays of characters.
h
• Each character has an index starting from 0.
text = "Python"
n
print(text[0]) # First character
print(text[3]) # Fourth character
print(text[-1]) # Last character (negative index)

4
Explanation:

P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

2. Accessing Multiple Characters Using Slicing


• Syntax: string[start:end] (End index is excluded)
• You can extract part of a string.

text = "Python"
print(text[0:4]) # From index 0 to 3 ("Pyth")
print(text[:3]) # From start to index 2 ("Pyt")
print(text[2:]) # From index 2 to end ("thon")
print(text[-3:]) # Last 3 characters ("hon")

6. Python strings are immutable. Justify with an example program.

STRINGS ARE IMMUTABLE

✓ In Python, strings are immutable, meaning once created, they cannot be changed.
✓ If you try to modify a string, a new string is created instead of modifying the existing one.
✓ Since strings cannot be modified directly, you must create a new string.

Example
str = "Hi"
str[0] = 'B' # Attempt to modify the first character
print(str)

✓ This will raise a TypeError: 'str' object does not support item assignment because modifying
a character directly is not allowed.

➢ Mutable objects are that we can modify according to our requirements and use according to
our use. A few examples of them are List, Dictionary, and Set.

Correct Way to Modify a String


Since strings are immutable, we need to create a new string instead:
str = "Hi"
new_str = "Bi" # Creating a new string Output:
print("Old String =", str) Old String = Hi
print("New String =", new_str) New String = Bi

✓ The original string remains unchanged.


✓ A new string object is created for the modification.

Deleting a String
• You cannot delete characters from a string, but you can delete the entire string using del:

str = "Hello"
del str # This deletes the variable reference, not modifying the string itself

Example Program
# Original string
greeting = "Good Morning" G o o d M o r n i n g

5 0 1 2 3 4 5 6 7 8 9 10 11
# Attempting to change a character (will cause an error)
try:
greeting[5] = 'E' # Trying to replace 'M' with 'E'
except TypeError as e:
print("Error:", e)
Output
# Correct way: Creating a new string
Error: 'str' object does not
new_greeting = greeting[:5] + 'E' + greeting[6:]
support item assignment
Original String: Good Morning
print("Original String:", greeting)
Modified String: Good Eorning
print("Modified String:", new_greeting)

Ways to Deal with Immutability


• String Slicing and Reassembling
• String Concatenation
• Using the join() method
• Using String Formatting
• Converting to Mutable Data Structures
Output
Python
1. String Slicing and Reassembling: Programming
String slicing allows you to extract a specific portion of a string. Python
text = "PythonProgramming"
print(text[0:6]) # Extracts "Python"
print(text[6:]) # Extracts "Programming" (from index 6 to end)
print(text[:6]) # Extracts "Python" (from start to index 6)

2. String Concatenation:
String concatenation refers to combining multiple strings into one.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)

3. Using the join() method:


The join() method is commonly used to concatenate multiple strings efficiently.
words = ["Hello", "world", "Python", "is", "awesome"] Output
sentence = " ".join(words) # Joins the words with a space Hello world Python is awesome
print(sentence)

4. Using String Formatting


String formatting allows you to insert values and variables into a string dynamically.
name = "Bob"
city = "New York" Output
print("Hello, my name is {} and I live in {}.".format(name, city)) Hello, my name is Bob and I
live in New York.

5. Converting to Mutable Data Structures


Strings in Python are immutable, meaning they cannot be changed after creation. However, you can
convert them into mutable data structures like lists to modify them.
s = "hello" Output
char_list = list(s) # Convert string to list of characters Hello
char_list[0] = "H" # Modify the first character
new_string = "".join(char_list) # Convert back to string
print(new_string)

6
15. Create a program to determine whether a string is a palindrome or not.

Algorithm

i. Start
ii. Input: Read a string from the user.
iii. Preprocess:
• Convert the string to lowercase to ensure case insensitivity.
• Remove spaces (if necessary) to allow for multi-word palindromes.
iv. Reverse the String:
• Create a reversed version of the string.
v. Compare:
• If the original string (after preprocessing) is the same as its reversed version, it is a
palindrome.
• Otherwise, it is not a palindrome.

vi. Output the result: Print whether the string is a palindrome or not.
vii. End

Program
def is_palindrome(s):
# Remove spaces and convert to lowercase for uniformity
s = s.replace(" ", "").lower()

# Compare string with its reverse


return s == s[::-1] Output

# Get user input Enter a string: madam


user_input = input("Enter a string: ") The string is a palindrome.

Enter a string: hello


# Check if it's a palindrome and display the result
The string is not a palindrome.
if is_palindrome(user_input):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

7. (i) Analyze string slicing. Illustrate how it is done in python with an example.
(ii) Write a python code to search a string in the given list.

(i) Analyze string slicing. Illustrate how it is done in python with an example.

✓ A substring of a string is called a slice.


✓ The slice operation is used to extract a subset of a string (or other sequences).
✓ Slicing Operator [ ] is used to perform slicing in Python.
✓ Purpose of Slicing: It helps in retrieving specific parts of a string without modifying the
original string.

7
Basic Syntax of String Slicing

String [start : end : step] • start: The starting index (included).


• end: The stopping index (excluded).
• step: The step size (optional, default is 1).
text = "Python Programming"
print(text[0:6]) # Output: Python
print(text[:6]) # Output: Python (start is optional, defaults to 0)
print(text[7:]) # Output: Programming (extracts from index 7 to end)
print(text[::2]) # Output: Pto rgamn (skips every alternate character)

(ii) Write a python code to search a string in the given list.


Output
def search_string(lst, target):
if target in lst: Enter a string to search: banana
print(f"'{target}' found in the list!") 'banana' found in the list!
else:
print(f"'{target}' not found in the list.")

# Given list of strings

8
string_list = ["apple", "banana", "cherry", "date", "elderberry"]

# Input from user


search_term = input("Enter a string to search: ")

# Call the function


search_string(string_list, search_term)

Explanation:
1. List of strings is predefined (string_list).
2. User inputs the string to search.
3. The program checks if the string exists in the list using in keyword.
4. If found, it prints "found"; otherwise, it prints "not found".

4. Write a Python program to count the number of vowels in a string provided by the user.

# Function to count vowels in a string


def count_vowels(text):
vowels = "aeiouAEIOU" # Define vowels (both lowercase and uppercase)
count = sum(1 for char in text if char in vowels) # Count vowels
return count

# Take input from user Output


user_string = input("Enter a string: ")
Enter a string: Hello World
Number of vowels in the string: 3
# Get vowel count
vowel_count = count_vowels(user_string)
Enter a string: Python Programming
Number of vowels in the string: 5
# Display the result
print(f"Number of vowels in the string: {vowel_count}")

Explanation:

✓ Define vowels (aeiouAEIOU) to consider both lowercase and uppercase.


✓ Loop through each character and check if it is in the vowel set.
✓ Use sum(1 for char in text if char in vowels) to count vowels efficiently.
✓ Display the total count.

11. Write a function that takes a string as a parameter and replaces the first letter of every word
with the corresponding uppercase letter.

Method 1: Using title()


def capitalize_words(string):
return string.title() Output

# Example usage Hello World, Python Is Awesome!


text = "hello world, python is awesome!"
print(capitalize_words(text))

Explanation:
✓ string.title() converts the first letter of every word in the string to uppercase and keeps
the rest lowercase.

9
✓ The function takes a string as input.
✓ The .title() method capitalizes the first letter of each word.
✓ The modified string is returned.

Method 2: Using split() and join()


def capitalize_words(string):
words = string.split() # Split the string into words
capitalized_words = [word[0].upper() + word[1:] if word else "" for word in words]
return " ".join(capitalized_words)

# Example usage Output


text = "hello world, python is awesome!"
Hello World, Python Is Awesome!
print(capitalize_words(text))

Explanation:
✓ The split() method breaks the string into a list of words based on spaces.
This is a list comprehension that processes each word:
✓ word[0].upper() → Converts the first letter of word to uppercase.
✓ word[1:] → Keeps the rest of the word unchanged.
✓ if word else "" → Handles empty strings (avoiding errors).
✓ The " ".join() method joins the list into a single string, adding spaces between words.

16. (i) Write a function to find the number of common characters in two strings.
(ii) Write a program to reverse a string.

(i) Write a function to find the number of common characters in two strings.
Output
Using set Intersection
def common_characters(s1, s2): 3
return len(set(s1) & set(s2)) # Find common unique characters
2
# Example usage
print(common_characters("apple", "grape")) # Output: 3 (a, p, e)
print(common_characters("hello", "world")) # Output: 3 (o, l)

Execution:

1. For "apple" and "grape"


o Unique characters in "apple" → {'a', 'p', 'l', 'e'}
o Unique characters in "grape" → {'g', 'r', 'a', 'p', 'e'}
o Common unique characters → { 'a', 'p', 'e' } → 3 characters
o Output: 3
2. For "hello" and "world"
o Unique characters in "hello" → {'h', 'e', 'l', 'o'}
o Unique characters in "world" → {'w', 'o', 'r', 'l', 'd'}
o Common unique characters → { 'o', 'l' } → 2 characters
o Output: 2

(ii) Write a program to reverse a string.


def reverse_string(s):

10
return s[::-1] # Slice with step -1 to reverse

# Example usage Output


text = "Hello, World!"
print(reverse_string(text)) !dlroW ,olleH

Explanation:

• Function Name: reverse_string(s)


o It takes a string s as input.
• String Slicing: s[::-1]
o s[start:end:step] is the syntax for slicing a string.
o [::-1] means:
▪ Start: Not specified (defaults to the beginning of the string).
▪ End: Not specified (defaults to the end of the string).
▪ Step: -1 (means move backwards, effectively reversing the string).

2. Write a program to count the number of common characters in a pair of strings.


# Function to count common characters
def count_common_chars(str1, str2):
# Convert both strings to sets to get unique characters
set1 = set(str1)
set2 = set(str2)

# Find intersection (common characters) and count them


common_chars = set1.intersection(set2)

return len(common_chars), common_chars Output:

# Input strings Enter first string: apple


string1 = input("Enter first string: ") Enter second string: grape
string2 = input("Enter second string: ")
Number of common characters: 3
# Get the count and common characters Common characters: a, p, e
count, chars = count_common_chars(string1, string2)
Enter first string: hello
# Display the result Enter second string: world
print(f"Number of common characters: {count}")
print(f"Common characters: {', '.join(chars)}") Number of common characters: 2
Common characters: o, l
✓ Convert each string into a set (set(str1), set(str2)) to get unique characters.
✓ Find the intersection of both sets to get common characters.
✓ Count the number of common characters using len().
✓ Display the result in a readable format.

11
3. Describe the methods and operations of Dictionaries.
14. Recollect the various dictionary operations and explain them with an example.

DICTIONARIES: OPERATIONS (CREATE, ACCESS, ADD, REMOVE) AND METHODS.

Dictionaries in Python

• A dictionary is a data structure that stores values as key-value pairs.


• Each key is separated from its value by a colon (:), and key-value pairs are separated by
commas.
• Curly brackets {} enclose dictionary items.

1. Creating a Dictionary

Syntax
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

student = {"name": "John", "age": 20, "course": "IT"}


print(student)
# Output: {'name': 'John', 'age': 20, 'course': 'IT'}

Key Properties
• Keys must be unique and immutable (e.g., strings, numbers, tuples).
• Values can be of any data type and do not need to be unique.
• Dictionaries are mappings, not sequences, meaning they store objects by key rather than
relative position.

Important Notes
• Keys are case-sensitive: "Key" and "key" are treated as different keys.
• Using a mutable object as a key causes a TypeError.

2. Accessing Values in a Dictionary:


• In Python, dictionaries store data in key-value pairs.
• To access values, use square brackets ([]) with the key inside.

12
Syntax :
dictionary_name[key]
Example:
student = {"name": "John", "age": 20, "course": "IT"}
print(student["name"]) # Output: John

✓ If a key does not exist, it raises a KeyError.

3.Adding and Modifying an Item in a Dictionary:

• In Python, dictionaries allow adding new key-value pairs or modifying existing ones using the
assignment operator (=).

Syntax
dictionary_variable[key] = value

Adding a New Key-Value Pair:

Example
student = {"name": "John", "age": 20}
student["course"] = "IT" # Adding a new key-value pair
print(student)
# Output: {'name': 'John', 'age': 20, 'course': 'IT'}

Modifying an Existing Key's Value:


student["age"] = 21 # Updating an existing key's value
print(student)
# Output: {'name': 'John', 'age': 21, 'course': 'IT'}

4. Deleting Items in a Dictionary:


Deleting a specific item: Use the del keyword with the key.
Syntax:
del dictionary_variable[key]

student = {"name": "John", "age": 20, "course": "IT"}


del student["age"]
print(student)
# Output: {'name': 'John', 'course': 'IT'}

Deleting all items: Use the .clear() function to remove all key-value pairs but keep the dictionary.

student.clear()
print(student)
# Output: {}

13
Deleting the entire dictionary: Use del to remove the dictionary from memory.

del student
print(student) # This will raise an error since 'student' no longer exists

5. Sorting Items in a Dictionary:

• Retrieving Keys: The .keys() method returns a list of all dictionary keys in arbitrary order.

student = {"name": "John", "age": 20, "course": "IT"}


print(student.keys())
# Output: dict_keys(['name', 'age', 'course'])

Sorting Dictionary Keys: The sorted() function sorts the keys in ascending order.
sorted_keys = sorted(student.keys())
print(sorted_keys)
# Output: ['age', 'course', 'name']

6. Merging Two Dictionaries

• Using .update() method:

dict1 = {"a": 1, "b": 2}


dict2 = {"b": 3, "c": 4}
dict1.update(dict2)
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}

METHODS OF DICTIONARIES

14
15
5. Write a program that takes a sentence as input from the user and computes the frequency of
each letter. Use a variable of dictionary type to maintain the count.

Program
sentence = input("Enter a sentence: ")
frequency = {} Output
for char in sentence: Enter a sentence: Hello World
if char.isalpha():
d : 1
char = char.lower()
e : 1
frequency[char] = frequency.get(char, 0) + 1
h : 1
l : 3
for letter, count in sorted(frequency.items()): o : 2
print(letter, ":", count) r : 1
w : 1
Explanation

✓ Uses a dictionary to store letter frequencies.


✓ create an empty dictionary named frequency.

16
✓ The dictionary will be used to store the count of each alphabet letter in the given sentence .
✓ for char in sentence:
This iterates through each character in the string sentence.
The loop variable char will take one character at a time from sentence.
✓ if char.isalpha():
This checks if char is an alphabet letter (i.e., it is not a space, number, or punctuation).
The .isalpha() method returns True for alphabet characters (a-z, A-Z) and False for anything
else.
✓ char = char.lower()
Converts char to lowercase to ensure that uppercase and lowercase letters are treated the
same.

✓ frequency[char] = frequency.get(char, 0) + 1

This updates the count of each letter in the dictionary.


.get(char, 0):
➢ If char is already in the dictionary, it retrieves its current count.
➢ If char is not in the dictionary, .get() returns 0.
Then, +1 is added to update the count.
The result is stored back in frequency[char].

✓ frequency.items() returns a list of key-value pairs from the dictionary.


✓ Count occurrences
h: 1
e: 1
l: 3
o: 2
w: 1
r: 1
d: 1
✓ sorted(frequency.items()) sorts them alphabetically by key (letter).

8. Using the concept of dictionary, write a program to create a dictionary that calculates the
frequency of words for a given text.

Program
def word_frequency(text):
word_count = {}
words = text.lower().split()

for word in words:


word = word.strip(".,!?;:'\"()")
word_count[word] = word_count.get(word, 0) + 1

return word_count

text = input("Enter text: ")


print(word_frequency(text))

Output
Enter text: hi! Chennai is the capital city of Tamilnadu. Chennai is the hub
for film production and studios.

17
{'hi': 1, 'chennai': 2, 'is': 2, 'the': 2, 'capital': 1, 'city': 1, 'of': 1,
'tamilnadu': 1, 'hub': 1, 'for': 1, 'film': 1, 'production': 1, 'and': 1,
'studios': 1}

Explanation
word_count = {}
✓ Creates an empty dictionary to store word counts.
words = text.lower().split()
✓ Converts all characters to lowercase to ensure case insensitivity.
✓ Splits the text into individual words.
for word in words:
✓ Iterates through each word in the list.
word = word.strip(".,!?;:'\"()")
✓ Cleans punctuation marks from each word.
word_count[word] = word_count.get(word, 0) + 1
✓ word_count is a dictionary that stores words as keys and their frequency as values.
✓ .get(word, 0) checks if word exists in word_count:
✓ If word exists, it returns its current count.
✓ If word does not exist, it returns 0 (default value).
✓ + 1 increases the count by 1.
✓ The updated value is assigned back to word_count[word].

Example
(First appearance of hello)
# word_count.get("hello", 0) → 0 (since "hello" is not yet in
the dictionary)
# 0 + 1 → 1
# word_count now becomes {'hello': 1}

(Second appearance of hello)


# word_count.get("hello", 0) → 1 (because "hello" is already in the
dictionary)
# 1 + 1 → 2
# word_count now becomes {'hello': 2}

12. Write a Python program for adding elements to a dictionary.

Program
# Initialize an empty dictionary Output
my_dict = {} Added (name: Alice) to dictionary.

# Function to add elements to the dictionary Added (age: 25) to dictionary.


def add_element(key, value): Added (city: New York) to
my_dict[key] = value dictionary.
print(f"Added ({key}: {value}) to dictionary.")
Updated Dictionary: {'name':
# Adding elements to the dictionary 'Alice', 'age': 25, 'city': 'New
York'}
add_element("name", "Alice")
add_element("age", 25)
add_element("city", "New York")

18
# Display the dictionary
print("Updated Dictionary:", my_dict)

Explanation
➢ We start with an empty dictionary called my_dict.
➢ def add_element(key, value):
✓ This function takes two parameters: key and value.
✓ It adds the key-value pair to the dictionary.
➢ add_element("name", "Alice")
add_element("age", 25)
add_element("city", "New York")
We call the function three times to add elements.
➢ Finally, we display the dictionary with the newly added elements.

SET AND SET OPERATIONS

9. Describe set and explain its operations with suitable examples.


18. Evaluate and explain the different operations like union, intersection and differences in a
Set with sample program.
SET
Definition:
✓ A set is a data structure in Python similar to a list but with no duplicate values.
✓ A set in Python is created using curly brackets {} or the built-in set() function.

Key Features:
• No Duplicates: Sets automatically remove duplicate values.
• Unordered: The elements in a set do not follow a specific order.
• Mutable: We can add or remove elements from a set.

Usage: Sets are useful when we need to store unique items and perform operations like union,
intersection, and difference efficiently.

1. Creating a Set

A set in Python is created using curly brackets {} or the built-in set() function.
Syntax
set_variable = {val1, val2, ...}
Example
s = {1, 2.0, "abc"}
print(s)
✓ This creates a set containing elements of different data types (integer, float, and string).

Using set() Function:


set([1, 2.0, 'abc'])
The set() function converts a list of values into a set.

Key Features:
✓ A set can store multiple types of data.
✓ It removes duplicate values automatically.
✓ Order of elements is not maintained.

19
No Duplicate Values in Sets
✓ Sets in Python do not allow duplicate values.
✓ If the same element is added multiple times, it is stored only once.

Example
# Creating a set with different data types and duplicate values
s = {1, 2.0, "hello", 2, "hello", 3.5, 2.0} Output

# Printing the set {1, 2.0, 'hello', 3.5}


print(s)

Example
Output
# Define two sets Union: {1, 2, 3, 4, 5, 6, 7, 8}
set1 = {1, 2, 3, 4, 5} Intersection: {4, 5}
set2 = {4, 5, 6, 7, 8} Difference (set1 - set2): {1, 2, 3}
Difference (set2 - set1): {8, 6, 7}
# Union of sets
union_set = set1 | set2 # or use set1.union(set2)
print("Union:", union_set)

# Intersection of sets
intersection_set = set1 & set2 # or use set1.intersection(set2)
print("Intersection:", intersection_set)

20
# Difference of sets (elements in set1 but not in set2)
difference_set = set1 - set2 # or use set1.difference(set2)
print("Difference (set1 - set2):", difference_set)

# Difference of sets (elements in set2 but not in set1)


difference_set2 = set2 - set1 # or use set2.difference(set1)
print("Difference (set2 - set1):", difference_set2)

10. Describe different functions associated with sets.

21
22
13. How to remove items from set? Explain the methods used for it with example.

SET
Definition:
✓ A set is a data structure in Python similar to a list but with no duplicate values.
✓ A set in Python is created using curly brackets {} or the built-in set() function.

Key Features:
• No Duplicates: Sets automatically remove duplicate values.
• Unordered: The elements in a set do not follow a specific order.
• Mutable: We can add or remove elements from a set.

1. remove() Method
• Removes the specified element from the set.
• If the element does not exist, it raises a KeyError.

23
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}

• If we try my_set.remove (10), it will raise a Key Error.


• Use when: You are sure that the item exists in the set.

2. discard() Method
• Removes the specified element from the set.
• If the element does not exist, it does not raise an error.

my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set) # Output: {1, 2, 4, 5}

• If we try my_set.discard(10), it will not raise an error.


• Use when: You want to remove an item, but don’t want your program to crash if it’s not found.

3. pop() Method
• Removes and returns a random element from the set.
• Since sets are unordered, we cannot predict which element will be removed.
• If the set is empty, it raises a KeyError.

my_set = {1, 2, 3, 4, 5}
removed_item = my_set.pop()
print(removed_item) # Output: (random element)
print(my_set) # Output: Remaining elements after pop

Use when: You just want to remove any item (e.g., when processing all items one-by-one).

Since sets in Python are unordered, the pop() method removes an element without following any
specific order. The element that gets removed depends on how Python internally stores the set's
elements, which can vary between executions.

my_set = {10, 20, 30, 40, 50}


print(my_set.pop()) # Might remove 10, 20, or any other element
print(my_set.pop()) # Might remove another random element

➢ Each time you run this code, it might remove a different element.

4. clear () Method
• Removes all elements from the set, making it empty.

my_set = {1, 2, 3, 4, 5}
my_set.clear()
print(my_set) # Output: set()

• If you’re not sure whether an item exists in a set and still want to remove it safely, use
discard () instead of remove ().

17. (i) Write a Python program to check if two given sets have no elements in common. (ii) Write a
Python program to remove the intersection of a 2nd set from the 1st set.

24
(i) Write a Python program to check if two given sets have no elements in common.
Program
# Function to check if two sets have no elements in common
def are_disjoint(set1, set2):
# Using isdisjoint() method Output
return set1.isdisjoint(set2)
set_a = {1, 2, 3}
# Example sets set_b = {4, 5}
set_a = {1, 2, 3, 4}
The sets have no elements
set_b = {5, 6, 7}
in common.
If:
# Check if they have no common elements set_a = {1, 2, 3}
if are_disjoint(set_a, set_b): set_b = {2, 4, 6}
print("The sets have no elements in common.")
else: The sets have some
print("The sets have some elements in common.") elements in common.

Explanation

• isdisjoint() is a built-in set method in Python.


• It returns True if no elements are common between the two sets.
• It returns False if at least one element is common.

(ii) Write a Python program to remove the intersection of a 2nd set from the 1st set.

✓ It will delete all elements from the first set that are also present in the second set.
Program
# Define two sets Output:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7} Set1 after removing intersection
with Set2: {1, 2, 3}
# Remove common elements (intersection) from set1
set1.difference_update(set2) Because 4 and 5 are
# Display the result
common to both sets,
print("Set1 after removing intersection with Set2:", set1) they are removed from
set1.
difference_update()

• It is a set method in Python.


• It removes all elements from the calling set (set1) that are also present in the given set
(set2).
• It modifies the original set in-place, meaning the original set1 is updated directly (no new
set is created).
• difference_update() does not return anything (None). It just changes the set.
• If there are no common elements, set1 stays the same.
• It's a faster and more memory-efficient way to update sets, especially useful for large
datasets.

25

You might also like