AppDividend
Latest Code Tutorials

How to Convert Python Tuple to Set

0

To create a tuple in Python, use the parentheses ( ), separated by commas. The parentheses are optional. A tuple can have many elements with different data types like integer, float, list, string, etc.

To create a set in Python, use the parentheses { }, separated by commas. The set consists of any number of elements, but it cannot contain duplicate elements. Set elements are unordered and unchangeable.

Convert Python Tuple to Set

To convert Python tuple to set, use the set() function. The set() is an inbuilt method used to convert any of the iterable to the sequence of iterable items with distinct items. The set() function takes iterables like list, tuple, dictionary, or string and returns the set.

Syntax

set(iterable)

Parameters

The set() takes any iterable sequence like list, tuple, or dictionary.

Return Value

It returns an empty set if you don’t pass any value to the set() function. Otherwise, it returns a non-repeating element iterable modified as passed as an argument.

Example

Define a tuple and convert it into a set using the set() function.

tpl = ("G", "R", "O", "G", "U")

# Printing tuple
print(type(tpl), " ", tpl)

# set() method convert set to tuple
s = set(tpl)
print("Converting tuple to set")

# printing tuple
print(type(s), " ", s)

Output

<class 'tuple'>   ('G', 'R', 'O', 'G', 'U')
Converting tuple to set
<class 'set'>   {'R', 'G', 'U', 'O'}

The type() function helps us to check the data type of value. In this example, we defined a tuple using curly braces({ }) and then use the type() function to check its data type. To convert the defined tuple into the set, we used the set() function and passed the tuple as an argument, and it returns a set.

Please note that when it returns set, then the duplicate elements of the tuple are removed from the set. For example, the GROGU elements have 2 G’s in the tuple, but when we converted it into the set, it returns RGUO, and the order is also changed. The duplicate G is removed from the set.

That means you can use the set() method to remove the duplicate elements from the iterables.

Passing no argument to set() function

If we don’t pass any arguments or pass the empty tuple to the set() function, it will return an empty set.

tpl = ()

# Printing tuple
print(type(tpl), " ", tpl)

# set() method convert set to tuple
s = set(tpl)
print("Converting tuple to set")

# printing tuple
print(type(s), " ", s)

Output

<class 'tuple'>   ()
Converting tuple to set
<class 'set'>   set()

We passed an empty tuple, and it returns an empty set.

That is it for converting tuple to set in Python.

See also

Python tuple to string

Python tuple to array

Python tuple to dict

Python tuple to list

Leave A Reply

Your email address will not be published.

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