[Python-3000] sets in P3K?

Edward Loper edloper at gradient.cis.upenn.edu
Wed Apr 26 04:33:12 CEST 2006


I think that a significant motivation for people that propose set 
literals is that the following is just plain ugly:

    s = set([1,2,3])

It seems much more natural to write:

    s = set(1, 2, 3)

However, it is fairly common to want to build a set from a collection, 
an iterator, or a genexp.  With the current notation, all three of these 
are easy.  But with this "more natural" notation, they're no longer 
possible without resorting to varargs (which would create an unnecessary 
imtermediary tuple).  I.e., we don't want to lose the ability to do any 
of the following:

   s = set(my_list)
   s = set(enumerate(my_list))
   s = set(x for x in collection if x>10)

One way around this conflict might be to define a new factory function, 
that generates a set from an iterable.  I.e., something like:

   s = set.from_iter(my_list)
   s = set.from_iter(enumerate(my_list))
   s = set.from_iter(x for x in collection if x>10)

(But with a better name than 'from_iter' :) )

The disadvantage, of course, is that it makes building sets from 
iterables less simple.  And this certainly might be enough of a 
disadvantage to rule out this solution.  But I thought I'd throw it out, 
anyway, to see what people think.

I'm personally +0 on this proposal if a good name can be thought of for 
the factory function; and -0 if a good name can't be thought of.

If this proposal does gain support, then it should presumably be applied 
to other data types as well, for consistency.  I.e.:
   l = list(1, 2, 3)
   l = list.from_iter([1, 2, 3])
   d = dict(('x', 'y'), ('a', 'b'))
   d = dict.from_iter((x,i) for (i,x) in enumerate(collection))
   t = tuple(1, 2, 3)
   t = tuple.from_iter(collection)

-Edward



More information about the Python-3000 mailing list