Last active
September 5, 2022 19:40
-
-
Save jonathanhle/c47c6f0117f7a88ad3415379f3f1a486 to your computer and use it in GitHub Desktop.
python map example
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
https://realpython.com/python-map-function/#coding-with-functional-style-in-python | |
# with a for loop | |
numbers = [1, 2, 3, 4, 5] | |
squared = [] | |
for num in numbers: | |
squared.append(num ** 2) | |
squared | |
#with a map | |
def square(number): | |
return number ** 2 | |
numbers = [1, 2, 3, 4, 5] | |
squared = map(square, numbers) | |
list(squared) | |
# another example | |
https://www.w3schools.com/python/ref_func_map.asp | |
def myfunc(a): | |
return len(a) | |
x = map(myfunc, ['apple', 'banana', 'cherry']) | |
print(x) | |
#convert the map into a list, for readability: | |
print(list(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment