0
$\begingroup$

In python, there is a syntax called generator expression. For example, [i for i in range(1,5)], [i**2 for i in range(1,5)], and [i**2 for i in range(1,5) if i%2==0] would return [1, 2, 3, 4], [1, 4, 9, 16], and [4, 16], respectively. (Here [...something...] represents the list structure in python).

However, I wonder how would a MMA user do in MMA. What is the best (i.e. easy and elegant) equivalent way? First, I could only come up with these methods:

Range[4]
#^2& /@ Range[4]
#^2& /@ (Select[EvenQ]@Range[4])
(* output is the same as above*)

Is it good enough? Is there other way?

The first question does not concern how the memory used, while the second question does: I've heard that the generator expression will not directly create the whole list in the memory. So when the size of the data structure to be iterated is huge, the memory can be saved and prevent the program from crashing. In MMA, it seems that to micmick the same mechaism would require a explicit While loop and so on? How would you do?

$\endgroup$
  • 3
    $\begingroup$ Faster alternatives (for longer lists) using vectorization: Range[4]^2, Range[2,4,2]^2. But what you are probably looking for are Table and Array. $\endgroup$ – Henrik Schumacher Apr 4 '18 at 8:12
  • $\begingroup$ AFAIK what you refer to in python is called list comprehensions (squared bracktes) not generator expressions (parenthesis). If you search this site for "list comprehension" you will find questions and answers which might make this a duplicate candidate. Generator expressions are similar but additionally are lazy, that means values are generated only on demand. The latter would be much more demanding to mimic in Mathematica. If you really are after generator expressions, you might want to search for lazy lists on this site... $\endgroup$ – Albert Retey Apr 4 '18 at 12:42
  • 1
    $\begingroup$ There are some undocumented features that are close equivalents of generators: iterators and streaming. Perhaps this means that we will have official built-in support for lazy lists in some future version. $\endgroup$ – WReach Apr 4 '18 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.