14
votes

In Python 2.6.5, given this list mylist = [20, 30, 25, 20]

Why does this set comprehension not work?

>>> {x for x in mylist if mylist.count(x) >= 2}
  File "<stdin>", line 1
    {x for x in mylist if mylist.count(x) >= 2}
         ^
SyntaxError: invalid syntax

Thank you.

2
Works for me with v2.7.2, I get set([20]) - Levon
What "doesn't work" about it? - kindall
Works for me in 3.2 also, though I'd note that {x for x, count in collections.Counter(mylist).items() if count >= 2} is O(n) instead of your O(n^2) approach. - Danica
Aha .. I can reproduce that error with v2.6.5 under Linux, so I bet you are using pre-v2.7. (My error message includes another line about SyntaxError: invalid syntax) - Levon

2 Answers

25
votes
$ python2.6
>>> mylist = [20, 30, 25, 20]
>>> {x for x in mylist if mylist.count(x) >= 2}
  File "<stdin>", line 1
    {x for x in mylist if mylist.count(x) >= 2}
         ^
SyntaxError: invalid syntax

$ python2.7
>>> mylist = [20, 30, 25, 20]
>>> {x for x in mylist if mylist.count(x) >= 2}
set([20])

You can accomplish the results in python2.6 using an explicit set, and a generator:

>>> set(x for x in mylist if mylist.count(x) >= 2)
set([20])
8
votes

What version of Python are you using? Set comprehensions appeared in 2.7.x+ and 3.x+. If you're using an older version, you'll get a SyntaxError: invalid syntax:

>>> {x for x in mylist if mylist.count(x) >= 2}
  File "<stdin>", line 1
    {x for x in mylist if mylist.count(x) >= 2}
         ^
SyntaxError: invalid syntax

That is not the case with Python 2.7.x+ / 3.x+ :

>>> {x for x in mylist if mylist.count(x) >= 2}
set([20])