Last active
June 29, 2017 15:34
-
-
Save codenameyau/91d9c4c747eec34b4906 to your computer and use it in GitHub Desktop.
Python lambda vs list comprehension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################ | |
# BASICS: LAMBDA VS LIST COMPREHENSION | |
################################################################ | |
# Filter | |
filter(lambda x: x % 2, range(10)) | |
[x for x in range(10) if x % 2] | |
# Map | |
map(lambda x: x*x, range(10)) | |
[x*x for x in range(10)] | |
# Reduce | |
reduce(lambda x, y: x+y, range(10)) | |
sum(range(10)) | |
################################################################ | |
# CHAIN IT UP | |
################################################################ | |
# Chain: level 1 | |
map(lambda x: x*x, filter(lambda x: x % 2, range(10))) | |
[x*x for x in range(10) if x % 2] | |
# Chain: level 2 | |
reduce(lambda x, y: x+y, map(lambda x: x*x, filter(lambda x: x % 2, range(10)))) | |
sum([x*x for x in range(10) if x % 2]) | |
################################################################ | |
# Filters | |
################################################################ | |
# Filters out None truthty values | |
L = [1, False, [], (), 42, None, True] | |
filter(bool, L) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python Logging