Python program to convert Set into Tuple and Tuple into Set
Last Updated :
07 Apr, 2023
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))
OutputThe converted tuple : (1, 2, 3, 4, 6, 7)
Algorithm:
- Initialize a set with some elements.
- Convert the set to a tuple using the unpacking operator (*).
- 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:
- Import the itertools module
- Initialize a set s with elements 'a', 'b', 'c', 'd', and 'e'
- Initialize an empty tuple t
- Use the itertools.chain() function to chain the elements of s and return a single iterable object
- Use the tuple() function to convert the iterable object to a tuple
- Assign the resulting tuple to variable t
- 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:
- Import the reduce function from the functools module.
- Create a set s containing the characters 'a', 'b', 'c', 'd', 'e'.
- Call the reduce function with three arguments: a lambda function, the set s, and an empty tuple as the initial value.
- The lambda function concatenates the current element x to the accumulator acc and returns the resulting tuple.
- The reduce function applies the lambda function to each element in s, updating the accumulator with the result of each step.
- 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))
OutputThe 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)]
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
7 min read
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
3 min read
Python - Convert List of Lists to Tuple of Tuples
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
8 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 fo
8 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 thi
10 min read
Convert Tuple Value List to List of Tuples - Python
We are given a dictionary with values as a list of tuples and our task is to convert it into a list of tuples where each tuple consists of a key and its corresponding value. Note: Each key will appear with each value from the list of tuples. For example: We have a dictionary dict = {'Gfg' : [(5, ),
4 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this tas
4 min read
Convert list of strings to list of tuples in Python
Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
5 min read
Generating a "Set Of Tuples" from A "List of Tuples" - Python
We are given a list of tuples and we need to extract only the unique tuples while removing any duplicates. This is useful in scenarios where you want to work with distinct elements from the list. For example:We are given this a list of tuples as [(1, 2), (3, 4), (1, 2), (5, 6)] then the output will
3 min read