0% found this document useful (0 votes)
7 views3 pages

Python Set Practice: 15 Solved Examples

Uploaded by

joyboyshesanand
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)
7 views3 pages

Python Set Practice: 15 Solved Examples

Uploaded by

joyboyshesanand
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

Python Set Practice - Solved Problems

1. Check if 'banana' is in the set

my_set = {"apple", "banana", "cherry"}

new = "banana" in my_set

print(new)

2. Add one item to a set

my_set = {"apple", "banana"}

my_set.add("orange")

print(my_set)

3. Add multiple items using update

my_set = {"apple", "banana"}

new = {"kiwi", "melon"}

my_set.update(new)

print(my_set)

4. Remove an item safely using discard

my_set = {"apple", "banana", "cherry"}

my_set.discard("orange")

print(my_set)

5. Print items in uppercase using set comprehension

my_set = {"python", "java", "go"}

lee = {[Link]() for x in my_set}

print(lee)

6. Union of two sets

a = {"apple", "banana"}

b = {"cherry", "banana"}
c = [Link](b)

print(c)

7. Intersection of two sets using &

a = {1, 2, 3}

b = {2, 3, 4}

c=a&b

print(c)

8. Difference of two sets

a = {1, 2, 3, 4}

b = {3, 4, 5}

c = [Link](b)

print(c)

9. Symmetric difference

a = {"apple", "banana", "cherry"}

b = {"banana", "kiwi"}

c = a.symmetric_difference(b)

print(c)

10. Check if two sets are disjoint

a = {1, 2, 3}

b = {6, 7, 9}

print(not(a & b))

11. Remove duplicates from list using set

nums = [1, 2, 2, 3, 4, 4, 5]

new = set(nums)

print(new)

12. Find all unique characters in string


text = "programming"

new = set(text)

print(new)

13. Count unique elements in two lists

a = [1, 2, 3, 4]

b = [3, 4, 5, 6]

unique_items = set(a + b)

print(len(unique_items))

14. Common vowels in two strings

s1 = "application"

s2 = "education"

vowels = {'a','e','i','o','u'}

vowels_S1 = set(s1)

vowels_S2 = set(s2)

vowels_S1.intersection_update(vowels)

vowels_S2.intersection_update(vowels)

new_list = vowels_S1 & vowels_S2

print(new_list)

15. Set comprehension: squares of even numbers

new_list = set(x**2 for x in range(1, 10) if x % 2 == 0)

print(sorted(new_list))

You might also like