Home > OS >  Make tuple of sets in Python
Make tuple of sets in Python

Time:01-29

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})

CodePudding user response:

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.

CodePudding user response:

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})
  • Related