-1

How should I interpret the following code?

return (e2 for e1 in edits1(word) for e2 in edits1(e1))

The edits1 function returns a list of words.

"Pass e1 into edits1(word), get the result, for each element in this resulting list, pass it to edits1(), and return the result"

Is this correct? Can anyone break the code down in english?

caesar
  • 185
  • 4
  • It isn't a list comprehension at all -- it is a generator expression – John Coleman Sep 08 '19 at 17:21
  • (…which uses the same kind of expression, but instead of resulting in a list it results in an iteration/generator.) – deceze Sep 08 '19 at 17:22
  • Please describe the content of edits1, and why do you iterate over the same list twice? – Saleem Ali Sep 08 '19 at 17:23
  • Without knowing what `edits1` actually does, it is hard to say. Based just on the name of the function, perhaps this is designed to generate words at edit distance 2. – John Coleman Sep 08 '19 at 17:26
  • (e for a in A for b in B) is like nested for a in A: for b in B. e is returned for each iteration on the resulting generator, if is a list e is appended to the list – geckos Sep 08 '19 at 17:27

2 Answers2

2

If it had been, return [e2 for e1 in edits1(word) for e2 in edits1(e1)] (note the square brackets), that would be a list comprehension which is equivalent to

def your_function():
    ....
    ....
    result = []
    for e1 in edits1(word):
        for e2 in edits1(e1):
            result.append(e2)
    return result

By using the round brackets, you are returning a generator which logically will give you the same set of values as a list comprehension but unlike list comprehension that creates all the values at once, the generator creates one value at a time as and when required.

PaxPrz
  • 1,778
  • 1
  • 13
  • 29
Shiva
  • 2,627
  • 21
  • 33
1

It basically is compact form of:

def generator_function():
    for e1 in edit1(word):
        for e2 in edit1(e1):
            yield e2

paranthesis ( ) returns a generator object

square braces [ ] returns a list

PaxPrz
  • 1,778
  • 1
  • 13
  • 29