Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active March 15, 2017 01:31
Show Gist options
  • Save louisswarren/813c5238742cb3d44438f736f3fca3cd to your computer and use it in GitHub Desktop.
Save louisswarren/813c5238742cb3d44438f736f3fca3cd to your computer and use it in GitHub Desktop.
Javascript's foreach in python
accumulate = lambda t: lambda f: lambda *a, **k: t(f(*a, **k))
@accumulate(list)
def foreach(iterable, func):
for i, x in enumerate(iterable):
yield func(x, i)
mylist = list(chr(n) for n in range(65, 75))
foreach(mylist, lambda x, i: print('{} => {}'.format(i, x)))
# 0 => A
# 1 => B
# 2 => C
# 3 => D
# 4 => E
# 5 => F
# 6 => G
# 7 => H
# 8 => I
# 9 => J
print(foreach(range(10), lambda n, _: n ** 2))
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
@louisswarren
Copy link
Author

louisswarren commented Mar 15, 2017

Javascript benefits from ignoring unneeded arguments, so that if you don't care about indices you can just not accept one in your lambda.

Python benefits from not being javascript.

[print('{} => {}'.format(i, x)) for i, x in enumerate(mylist)]
print([n ** 2 for n in range(10)])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment