Make tuple of sets in Python

Question:

I want to put two sets in a tuple in Python.

set1 = set(1, 2, 3, 4)
set2 = set(5, 6, 7)

What I’ve tried:

result = tuple(set1, set2)
# got error "TypeError: tuple expected at most 1 argument, got 2"

Desired output:

({1, 2, 3, 4}, {5, 6, 7})
Asked By: cinnamon

||

Answers:

set and tuple constructors take only one argument: an iterable. Wrap your arguments in a list and it should work.

set1 = set([1, 2, 3, 4])
set2 = set([5, 6, 7])
result = tuple([set1, set2])  # or (set1, set2)
print(result)  # ({1, 2, 3, 4}, {5, 6, 7})
Answered By: Fractalism

A tuple literal is just values separated by commas.

set1 = {1,2,3,4}
set2 = {5,6,7}
result = set1, set2

or if you find it clearer

result = (set1, set2)

The tuple(x) form is useful when you have an iterable sequence x that you want to transform to a tuple.

Answered By: khelwood
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.