Skip to content

Instantly share code, notes, and snippets.

@milesrout
Forked from louisswarren/foreach.py
Created March 15, 2017 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milesrout/2ea0dbe72084e10fddca4d9019ea73a7 to your computer and use it in GitHub Desktop.
Save milesrout/2ea0dbe72084e10fddca4d9019ea73a7 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]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment