tags:

views:

100

answers:

3

I only just noticed this feature today!

s={1,2,3} #Set initialisation
t={x for x in s if x!=3} #Set comprehension
t=={1,2}

What version is it in? I also noticed that it has set comprehension. Was this added in the same version?

Resources

A: 

Well, testing it:

>>> s = {1, 2, 3}
  File "<stdin>", line 1
    s = {1, 2, 3}
          ^
SyntaxError: invalid syntax

I'm running 2.5, so I would assume that this syntax was added sometime in 2.6 (Update: actually added in 3.0, but Ian beat me). I should probably be upgrading sometime soon. I'm glad they added a syntax for it - I'm rather tired of set([1, 2, 3]).

Set comprehensions have probably been around since sets were first created. The Python documentation site isn't very clear, but I wouldn't imagine sets would be too useful without iterators.

Chris Lutz
I guess I wasn't clear enough in the question. This is when sets were added and set operators. Don't downvote this answer
Casebash
+6  A: 

The sets module was added in Python 2.3, but the built-in set type was added to the language in 2.4, with essentially the same interface. (As of 2.6, the sets module has been deprecated.)

So you can use sets as far back as 2.3, as long as you

import sets

But you will get a DeprecationWarning if you try that import in 2.6

Set comprensions, and the set literal syntax -- that is, being able to say

a = { 1, 2, 3 }

are new in Python 3.0. To be very specific, both set literals and set comprehensions were present in Python 3.0a1, the first public release of Python 3.0, from 2007.

Python 3 release notes

Ian Clelland
Again, this doesn't answer the question, but it is my fault for being unclear
Casebash
The special set comprehension syntax with brackets is new to Python 3.0, but you can perform set comprehensions in 2.5 and older with the more verbose (and uglier) `set([i for i in s])`
Chris Lutz
It is listed as a new feature in Python 3.0. http://docs.python.org/dev/3.0/whatsnew/3.0.html. It can't be done in Python 2.6
Casebash
@Chris: Use a generator expression, it allows to drop the brackets if alone, `set(i for i in s)`. Not ugly IMO.
kaizer.se
A: 

The set literal and set and dict comprehension syntaxes were backported to 2.x trunk, about 2-3 days ago. So I guess this feature should be available from python 2.7.

vshenoy