Python Program to Convert Set into Tuple and Tuple into Set

Convert set to tuple

Here are 3 ways: 

  1. Using tuple()
  2. Using list comprehension
  3. Using enumerate()

Method 1: Using tuple()

The tuple() function takes an iterable(a set) and returns a new tuple containing the elements from the iterable.

To check the data type, use the type() function.

Visual Representation

Visual Representation of Convert set to tuple

Example

# Define a set
original_set = {2, 4, 6, 8, 10}
print(type(original_set))

# Convert set to tuple
original_tuple = tuple(original_set)

print(original_tuple)
print(type(original_tuple))

Output

<class 'set'>
(2, 4, 6, 8, 10)
<class 'tuple'>

Method 2: Using list comprehension

You can iterate through the set in the list comprehension and then convert the resulting list to a tuple.

Visual RepresentationVisual Representation of Using list comprehensionExample

original_set = {2, 4, 6, 8, 10}
print(type(original_set))

original_tuple = tuple([item for item in original_set])

print(original_tuple)
print(type(original_tuple))

Output

<class 'set'>
(2, 4, 6, 8, 10)
<class 'tuple'>

Method 3: Using enumerate()

original_set = {2, 4, 6, 8, 10}
print(type(original_set))

original_tuple = tuple(item for index, item in enumerate(original_set))

print(original_tuple)
print(type(original_tuple))

Output

<class 'set'>
(2, 4, 6, 8, 10)
<class 'tuple'>

Convert tuple to set

Here are 3 ways: 

  1. Using set()
  2. Using list comprehension
  3. Using Unpacking (*) 

Method 1: Using set()

The set() method takes an iterable (like a tuple) and returns a new set with the elements from the iterable.

Visual Representation

Visual Representation of Convert tuple to set

Example

original_tuple = (2, 4, 6, 8, 10)
print(type(original_tuple))

# Convert the tuple to a set
original_set = set(original_tuple)

print(original_set)
print(type(original_set))

Output

<class 'tuple'>
{2, 4, 6, 8, 10}
<class 'set'>

Method 2: Using list comprehension

original_tuple = (2, 4, 6, 8, 10)
print(type(original_tuple))

original_set = set([item for item in original_tuple])

print(original_set)
print(type(original_set))

Output

<class 'tuple'>
{2, 4, 6, 8, 10}
<class 'set'>

Method 3: Using Unpacking (*) 

Visual Representation

Visual Representation of Using Unpacking

Example

original_tuple = (2, 4, 6, 8, 10)
print(type(original_tuple))

original_set = {*original_tuple}

print(original_set)
print(type(original_set))

Output

<class 'tuple'>
{2, 4, 6, 8, 10}
<class 'set'>

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.