Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Set to Tuple | Tuple to Set | 3 Easy Ways

#1
Python Set to Tuple | Tuple to Set | 3 Easy Ways

5/5 – (1 vote)

? Problem Formulation: Given a Python set. How to convert it to a tuple? And how to convert the tuple back to a set?

There are three main ways:

  • Method 1: To convert a Python set to a tuple, use the tuple(my_set) function.
  • Method 2: To convert a Python tuple to a set, use the set(my_tuple) function.
  • Method 3: To convert a Python tuple of mutable elements to a set, use the expression set(tuple(x) for x in my_tuple) to avoid a TypeError.

I’ll also give you a bonus method 4 that shows you what to do to retain the ordering information when converting a tuple to a set—so keep reading! ?

Method 1: Convert Set to Tuple with tuple()


To convert a set to a tuple, pass the set into the tuple() function. This is a built-in Python function, so you don’t need to import or install any library to use it. The return value is a new tuple from the values in the set.

? Here’s an example where you convert the set {1, 2, 3} to a tuple (1, 2, 3):

my_set = {1, 2, 3}
my_tuple = tuple(my_set)
print(my_tuple)
# (1, 2, 3)

By the way, here’s an explainer video on this function:

YouTube Video

Method 2: Convert Tuple to Set with set()


To convert a tuple to a set, pass the tuple into the set() function. This is a built-in Python function, so you don’t need to import or install any library. The return value is a new set from the values in the tuple.

? Here’s an example where you convert the tuple (1, 2, 3) to a set {1, 2, 3}:

my_tuple = (1, 2, 3)
my_set = set(my_tuple)
print(my_set)
# {1, 2, 3}
YouTube Video

⚡ Problem: However, the conversion process from a tuple to set doesn’t always work because if you try to convert a tuple of mutable values, Python will raise the TypeError: unhashable type!

Read on to learn more about this problem—and how to resolve it easily: ?

Method 3: Convert Tuple to Set with Set Comprehension


? A Python set is an unordered collection of unique immutable elements. Each element must define explicitly or implicitly the __hash__() dunder method, i.e., must be hashable.

If you attempt to convert a tuple of mutable elements (e.g., lists) to a set, Python will raise an error such as the TypeError: unhashable type: 'list':

my_tuple = ([1, 2], [3, 4], [5, 6])
my_set = set(my_tuple)
# TypeError: unhashable type: 'list'

In this case, you can use set comprehension to convert each inner tuple element to an immutable type. For example, the expression set(tuple(x) for x in my_tuple) converts each inner list to a tuple. The result is a set of immutable tuples.

Here’s the solution to this problem in a minimal code example:

my_tuple = ([1, 2], [3, 4], [5, 6])
my_set = set(tuple(x) for x in my_tuple)
print(my_set)
# {(1, 2), (3, 4), (5, 6)}

The final “bonus” section introduces another elegant way to retain the ordering information in a set:


Bonus Method 4: Enumerate Elements


Sometimes, you want to associate each set or tuple element with a specific numerical “index” value, i.e., a unique integer identifier. The enumerate() method to the rescue!

YouTube Video

  • Use tuple(enumerate(my_set)) to convert a set to an enumerated tuple.
  • Use set(enumerate(my_tuple)) to convert a tuple to an enumerated set.

The result is the respective container data structure with (identifier, value) tuples:

my_set = {'Alice', 'Bob', 'Carl'} my_tuple = tuple(enumerate(my_set))
print(my_tuple)
# ((0, 'Carl'), (1, 'Bob'), (2, 'Alice')) my_set = set(enumerate(('Alice', 'Bob', 'Carl')))
print(my_set)
# {(2, 'Carl'), (0, 'Alice'), (1, 'Bob')}

Especially in the case where you convert a tuple to a set, this makes a lot of sense because you can retain the information on the ordering of elements that would be otherwise lost after converting to a set.


Thanks for reading the whole article, my friend! You can join us here (we have cheat sheets too):



https://www.sickgaming.net/blog/2022/09/...easy-ways/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] 5 Expert-Approved Ways to Remove Unicode Characters from a Python Dict xSicKxBot 0 16 Today, 04:51 AM
Last Post: xSicKxBot
  [Tut] Python IndexError: Tuple Index Out of Range [Easy Fix] xSicKxBot 0 1,950 08-22-2023, 09:07 AM
Last Post: xSicKxBot
  [Tut] Python Tuple Concatenation: A Simple Illustrated Guide xSicKxBot 0 1,943 08-21-2023, 10:25 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,697 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Python Snake Made Easy xSicKxBot 0 1,219 04-25-2023, 05:36 PM
Last Post: xSicKxBot
  [Tut] Python ? Put Legend Outside Plot ? – Easy Guide xSicKxBot 0 1,468 04-22-2023, 11:08 PM
Last Post: xSicKxBot
  [Tut] Easy Way to Update a Python Package with Pip Upgrade xSicKxBot 0 1,384 03-19-2023, 12:16 PM
Last Post: xSicKxBot
  [Tut] I Created My First DALL·E Image in Python OpenAI Using Four Easy Steps xSicKxBot 0 1,279 03-10-2023, 03:46 PM
Last Post: xSicKxBot
  [Tut] 5 Easy Ways to Edit a Text File From Command Line (Windows) xSicKxBot 0 1,324 03-05-2023, 08:32 AM
Last Post: xSicKxBot
  [Tut] EzpzShell: An Easy-Peasy Python Script That Simplifies Revshell Creation xSicKxBot 0 1,347 02-11-2023, 10:30 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016