Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this set comprehension work?

Tags:

python

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.

like image 324
octopusgrabbus Avatar asked Jul 15 '12 00:07

octopusgrabbus


People also ask

How do you use set comprehension in Python?

In the statement “newSet = {element *3 for element in myList if element % 2 == 0}”, Set comprehension is used to create the newSet which contains squares of the even elements in myList. If we compare the code with the syntax for set comprehension, the following observation can be made.

Is there set comprehension in Python?

Yep, there is a Set Comprehension syntax in Python, which many people don't know.

What are the major differences of a set comprehension versus a list comprehension?

A set comprehension is similar to a list comprehension but returns a set instead of a list. The syntax is slightly different in the sense that we use curly brackets instead of square brackets to create a set. The list includes a lot of duplicates, and there are names with only a single letter.

Why do tuples not support comprehension?

There is no tuple comprehension in Python. Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.


1 Answers

$ 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])
like image 188
jdi Avatar answered Oct 21 '22 07:10

jdi