pythonsetiterable-unpacking

Python assign tuple to set() without unpacking


How can I assign a tuple to a set without the members being unpacked and added separately?

For example (python 3.9.11):

from collections import namedtuple
Point = namedtuple('Point', 'x y')
p = Point(5, 5)
set(p)

produces {5}, whereas I would like {Point(5, 5)}


Solution

  • If you want to make a set from a specific number of individual values, just use a set literal:

    {p}
    

    If you must, for some reason, specifically use the set constructor, just wrap the item in question in some other container literal before passing it to set, e.g.:

    set((p,))
    set([p])
    set({p})  # Maximal redundancy
    

    but all of them will be slower and uglier than just using the set literal. The only time people typically would do this is in code written for ancient Python (from when set was introduced in 2.4 until 2.6, the set constructor was the only way to make a set; in 2.7 and higher, the set literal syntax was available).


    Minor side-note: Be aware that {} is an empty dict, not a set. To make an empty set, you typically use set() (or {*()}, the one-eyed monkey "operator", if you're having fun). But as long as you have at least one item to put in the set literal, it works (it can tell it's a set because you didn't use : to separate key-value pairs).