Q:

Check if two sets have any elements in common. If yes, display the common elements using python programming

belongs to collection: Python Set Exercises

0

Check if two sets have any elements in common. If yes, display the common elements

Given:

set1 = {10, 20, 30, 40, 50}
set2 = {60, 70, 80, 90, 10}

Expected output:

Two sets have items in common
{10}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  • Use the isdisjoint() method check if sets has a common elements
  • If above condition is true then use the intersection() method to display common elements

Solution:

set1 = {10, 20, 30, 40, 50}
set2 = {60, 70, 80, 90, 10}

if set1.isdisjoint(set2):
  print("Two sets have no items in common")
else:
  print("Two sets have items in common")
  print(set1.intersection(set2))

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Update set1 by adding items from set2, except comm... >>
<< Return a set of elements present in Set A or B, bu...