Skip to content

Instantly share code, notes, and snippets.

@jonathanhle
Last active September 5, 2022 19:40
Show Gist options
  • Save jonathanhle/c47c6f0117f7a88ad3415379f3f1a486 to your computer and use it in GitHub Desktop.
Save jonathanhle/c47c6f0117f7a88ad3415379f3f1a486 to your computer and use it in GitHub Desktop.
python map example
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