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.
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.
Yep, there is a Set Comprehension syntax in Python, which many people don't know.
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.
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.
$ 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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With