Reputation: 118792
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
Upvotes: 4
Views: 1696
Reputation: 44122
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 comprehensions, 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
The comprehensions and literals were later implemented in 2.7. 3.x Python features incorporated into 2.7
Upvotes: 12
Reputation: 1213
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.
Upvotes: 0
Reputation: 75399
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.
Upvotes: 0