Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Last active July 7, 2022 22:54
Show Gist options
  • Select an option

  • Save onelharrison/517d6d90cccfeba150a194e55d138362 to your computer and use it in GitHub Desktop.

Select an option

Save onelharrison/517d6d90cccfeba150a194e55d138362 to your computer and use it in GitHub Desktop.
Code snippet showing the use of anonymous functions in Python
from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
if __name__ == "__main__":
people = [
Person("Marie Curie", 66),
Person("Katherine Johnson", 101),
Person("Ada Lovelace", 36),
]
first_names = list(map(lambda p: p.name.split(" ")[0], people))
print(first_names) # ["Marie", "Katherine", "Ada"]
# Filter the list to only people with name starting with 'A' and print it
people_with_names_starting_with_a = list(filter(lambda p: p.name.startswith("A"), people))
print(people_with_names_starting_with_a)
# Sort the list by name and print it
print(sorted(people, key=lambda p: p.name))
# Sort the list by age and print it
print(sorted(people, key=lambda p: p.age))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment