Created
December 28, 2015 14:02
-
-
Save andreisoriga/a71c9250bedfc60d0b09 to your computer and use it in GitHub Desktop.
Common lambda functions
This file contains hidden or 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
# square | |
sq = lambda x: x * x | |
sq(99) # 9801 | |
# sum rgb | |
rgb = lambda r, g, b: r + g + b | |
rgb(45, 22, 35) # 102 | |
# remove duplicate values from iterable | |
remove_duplicates = lambda iterable: list(set(iterable)) | |
remove_duplicates("roooot") # ['o', 't', 'r'] | |
remove_duplicates([1, 2, 2, 3, 4, 4]) # [1, 2, 3, 4] | |
# Convert list to int | |
convert_list_to_int = lambda iterable: map(int, iterable) | |
convert_list_to_int(['123', '34', '5667']) # 123, 34, 5667[] | |
# map - returns an iterator that applies a function to every item of iterable and yields the result | |
# Print list elements with separator | |
lst = [34, '234234', 566] | |
print(*lst, sep='\n') | |
# Check if number is even | |
is_even = lambda num: num % 2 == 0 | |
is_even(2) # True | |
# Get all even items from a list / range | |
evens = lambda lst: filter(is_even, lst) | |
evens([2, 1, 22]) # [2, 22] | |
# filter - construct an iterator from those elements of iterable for which function returns true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment