Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell.
Do they allow things like multiple generators? Or are they just a basic map-filter form?
If they don't allow multiple generators, I find them quite disappointing - why have such things been left out?
Set comprehension is a method for creating sets in python using the elements from other iterables like lists, sets, or tuples. Just like we use list comprehension to create lists, we can use set comprehension instead of for loop to create a new set and add elements to it.
In this article, I have introduced all the 4 types of comprehensions in Python — List, Dictionary, Set and Generator Comprehension. Most of the time, they are very elegant, concise and even can improve the readability of our code.
Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined. Python supports the following 4 types of comprehensions: List Comprehensions.
If you're wondering if JavaScript supports a list comprehension syntax like Python, the answer is unfortunately no. The JavaScript Committee TC39 once considered adding list comprehension to JavaScript, but it was canceled in favor of other JavaScript array methods like filter() and map() .
Python allows multiple generators:
>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5)]
[(1, 1, 1), (1, 2, 2), (1, 3, 3), (1, 4, 4),
(2, 1, 2), (2, 2, 4), (2, 3, 6), (2, 4, 8),
(3, 1, 3), (3, 2, 6), (3, 3, 9), (3, 4, 12),
(4, 1, 4), (4, 2, 8), (4, 3, 12), (4, 4, 16)]
And also restrictions:
>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5) if x*y > 8]
[(3, 3, 9), (3, 4, 12), (4, 3, 12), (4, 4, 16)]
Update: Javascript's syntax is similar (results from using the javascript shell on firefox):
var nums = [1, 2, 3, 21, 22, 30];
var s = eval('[[i,j] for each (i in nums) for each (j in [3,4]) if (i%2 == 0)]');
s.toSource();
[[2, 3], [2, 4], [22, 3], [22, 4], [30, 3], [30, 4]]
(For some reason, something about the context stuff is evaluated in in the javascript shell requires the eval indirection to have list comprehensions work. Javascript inside a <script>
tag doesn't require that, of course)
Yes, you can have multiple iterables in a Python list comprehension:
>>> [(x,y) for x in range(2) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
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