Fork me on GitHub
#other-languages
<
2024-04-29
>
grav15:04:44

This is one-level flatten in Python:

def flatten(lst):
    return [e for es in lst for e in es]

grav15:04:57

For some reason I have a hard time grasping it 😕

grav15:04:54

First part, e for es in lst is simple - but then it seems the last part for e in es ... hm ... somhow operates on the same es? But that e is a different e?

Noah Bogart15:04:16

these are written in a DSL that's like nested loops but without the indentation

Noah Bogart15:04:08

return [e for es in lst for e in es] can be read like this:

ret = []
for es in lst:
    for e in es:
      ret.append(e)
return ret

👍 1
Noah Bogart15:04:10

that is to say the [e for ...] is like saying append to a new list each of e. and then for es in lst and for e in es are two for loops but flattened into the list comprehension

Noah Bogart15:04:09

clojure does it in the reverse: (for [es lst e es] e)

💡 1
Noah Bogart15:04:24

for es in lst, for e in es, return a sequence of e

grav15:04:31

Ah, yes so it's read as

python'ish
for es in lst
   for e in es
      e
so
clojure
(for [es lst
        e es]
   e)

👍 1