Common Values of sets

Viewed 24

Say I have 3 sets and want to find print the common values. Is there a more efficient way to write the code?

This is what I came up with:

    s1= {1, 2, 3}
    s2 = {2, 3, 4}
    s3 = {3, 4, 5}
    for i in s1:
        for x in s2:
            for z in s3:
                if i == x == z:
                    print(i)

Thank you in advance!

2 Answers

Use the set.intersection method:

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}

print(s1.intersection(s2).intersection(s3))

Result:

{3}

Also you can use this method :

s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = {3, 4, 5}


if (s1 & s2 & s3 ):
    print(s1 & s2 & s3)
else :
    print("No common elements.")

Result :

{3}
Related