Open In App

Python program to convert Set into Tuple and Tuple into Set

Last Updated : 07 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Let’s see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type().

  • tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.
  • set(): set method is to convert other type values to set this method is also accepted other type values as an argument and return a set type value.
  • type(): type method helps the programmer to check the data type of value. This method accepts a value as an argument and it returns type of the value.

Example:

Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
Explanation: converting Set to tuple

Input: ('x', 'y', 'z')
Output: {'z', 'x', 'y'}
Explanation: Converting tuple to set

Example 1: convert set into tuple.

Python




#   program to convert set to tuple
# create set
s = {'a', 'b', 'c', 'd', 'e'}
 
# print set
print(type(s), " ", s)
 
# call tuple() method
# this method convert set to tuple
t = tuple(s)
 
# print tuple
print(type(t), " ", t)


Output

(<type 'set'>, ' ', set(['a', 'c', 'b', 'e', 'd']))
(<type 'tuple'>, ' ', ('a', 'c', 'b', 'e', 'd'))

Time complexity: O(n), where n is the number of elements in the set.
Auxiliary space: O(n), where n is the number of elements in the set, due to the creation of a new tuple.

Method2: Using list comprehension

Python3




s = {'a', 'b', 'c', 'd', 'e'}
x=[i for i in s]
print(tuple(x))


Output

('a', 'd', 'b', 'c', 'e')

Time complexity: O(n), where n is the size of the set s.
Auxiliary space: O(n), as we are creating a list x with n elements, where n is the size of the set s

Method #3: Using enumerate function

Python3




s = {'a', 'b', 'c', 'd', 'e'}
x=[i for a,i in enumerate(s)]
print(tuple(x))


Output

('e', 'a', 'd', 'b', 'c')

The time complexity of the program is O(n), where n is the size of the set s. 

The auxiliary space of the program is also O(n), where n is the size of the set s. 

Example #2: tuple into the set.

Step-by-step approach:

  • Create a tuple t with three elements: ‘x’, ‘y’, and ‘z’.
  • Print the type of t and its contents using print(type(t), ” “, t).
  • Call the set() method with t as its argument. This creates a new set s with the same elements as t, but in an arbitrary order.
  • Print the type of s and its contents using print(type(s), ” “, s). The output will show that s is a set containing ‘x’, ‘y’, and ‘z’.

Below is the implementation of the above approach:

Python




#program to convert tuple into set
 
# create tuple
t = ('x', 'y', 'z')
 
# print tuple
print(type(t), "  ", t)
 
# call set() method
s = set(t)
 
# print set
print(type(s), "  ", s)


Output

(<type 'tuple'>, '  ', ('x', 'y', 'z'))
(<type 'set'>, '  ', set(['y', 'x', 'z']))

Time complexity: O(n), where n is the size of the input tuple. The reason being, the program iterates through each element of the tuple once to convert it into a set.
Auxiliary space: O(n) as well, where n is the size of the input tuple. The reason being, the program creates a new set containing all elements of the tuple, which requires additional memory space equivalent to the size of the input tuple.

Method #4: Using the ‘*’ operator the ‘*’ operator can be used to unpack the elements of a set into a tuple.

Python3




#initializing a set
test_set = {6, 3, 7, 1, 2, 4}
 
#converting the set into a tuple
test_tuple = (*test_set,)
 
#printing the converted tuple
print("The converted tuple : " + str(test_tuple))


Output

The converted tuple : (1, 2, 3, 4, 6, 7)

Algorithm:

  1. Initialize a set with some elements.
  2. Convert the set to a tuple using the unpacking operator (*).
  3. Print the converted tuple.

Time Complexity: The time complexity of the code is O(n) because converting a set to a tuple, using the unpacking operator (*), takes linear time.
Auxiliary Space: The auxiliary space complexity of the code is O(n) because the tuple size is proportional to the set size.

Method #3: Using the += operator

We initialize an empty tuple t. Then we loop through each element i in the set s. For each element, we create a one-element tuple (i,) and concatenate it to the existing tuple t using the += operator. Finally, we print the resulting tuple t. This approach does not use list comprehension and instead uses a loop and tuple concatenation to create the final tuple.

Python3




s = {'a', 'b', 'c', 'd', 'e'}
 
# initialize an empty tuple
t = tuple()
 
# loop through each element in the set s
for i in s:
    # create a one-element tuple with the current element i and concatenate it to t
    t += (i,)
 
# print the resulting tuple
print(t)


Output

('a', 'c', 'd', 'e', 'b')

Time Complexity: O(n) because converting a set to a tuple, using the unpacking operator (*), takes linear time.
Auxiliary Space: O(n) because the tuple size is proportional to the set size.

Method #4:Using itertools library’s tuple() function.
Algorithm:

  1. Import the itertools module
  2. Initialize a set s with elements ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’
  3. Initialize an empty tuple t
  4. Use the itertools.chain() function to chain the elements of s and return a single iterable object
  5. Use the tuple() function to convert the iterable object to a tuple
  6. Assign the resulting tuple to variable t
  7. Print the tuple t

Python3




import itertools
#initializing set
s = {'a', 'b', 'c', 'd', 'e'}
t = tuple(itertools.chain(s))
# print the resulting tuple
 
print(t)


Output

('b', 'a', 'e', 'd', 'c')

Time Complexity:
The time complexity of the chain() function in the itertools module is O(n), where n is the total number of elements in the set s. 

Auxiliary Space: 

The Auxiliary Space of the code is O(n), where n is the number of elements in the set s.

Method #5:  Using reduce():

Algorithm:

  1. Import the reduce function from the functools module.
  2. Create a set s containing the characters ‘a’, ‘b’, ‘c’, ‘d’, ‘e’.
  3. Call the reduce function with three arguments: a lambda function, the set s, and an empty tuple as the initial value.
  4. The lambda function concatenates the current element x to the accumulator acc and returns the resulting tuple.
  5. The reduce function applies the lambda function to each element in s, updating the accumulator with the result of each step.
  6. The final value of the accumulator is the resulting tuple t and print the resulting tuple t.

Below is the implementation of the above approach:

Python3




# Python program for the above approach
from functools import redu
 
s = {'a', 'b', 'c', 'd', 'e'}
t = reduce(lambda acc, x: acc + (x,), s, ())
 
# Print the converted tuple
print("The converted tuple : " + str(t))


Output

The converted tuple : ('e', 'c', 'b', 'd', 'a')

Time Complexity:

The time complexity of this code is O(n), where n is the number of elements in the set s. This is because the reduce function processes each element in s exactly once, and each operation takes constant time

Space Complexity:

The space complexity of this code is O(n), where n is the number of elements in the set s. This is because the reduce function creates a new tuple for each element in s, so the total space used is proportional to n. However, since tuples are immutable in Python, this does not create any significant memory overhead. The lambda function and the initial empty tuple also take constant space, so they do not contribute to space complexity.



Similar Reads

Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python program to convert tuple into list by adding the given string after every element
Given a Tuple. The task is to convert it to List by adding the given string after every element. Examples: Input : test_tup = (5, 6, 7), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg', 7, 'Gfg'] Explanation : Added "Gfg" as succeeding element. Input : test_tup = (5, 6), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg'] Explanation : Added "Gfg" as succeeding element
5 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python | Convert a List into a Tuple
Given a list, write a Python program to convert the given list into a Python tuple. Examples: Input : [1, 2, 3, 4]Output : (1, 2, 3, 4)Input : ['a', 'b', 'c']Output : ('a', 'b', 'c')Convert a list into a tuple using tuple()Using tuple(list_name). Typecasting to tuple can be done by simply using tuple(list_name). C/C++ Code # Python3 program to conv
3 min read
Python | Convert a list into tuple of lists
We are given a list, the task is to convert the list into tuple of lists. Input: ['Geeks', 'For', 'geeks'] Output: (['Geeks'], ['For'], ['geeks'])Input: ['first', 'second', 'third'] Output: (['first'], ['second'], ['third']) Method #1: Using Comprehension C/C++ Code # Python code to convert a list into tuple of lists # Initialisation of list Input
4 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task. I
8 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
three90RightbarBannerImg