Skip to content

Instantly share code, notes, and snippets.

@drmingle
Created May 5, 2018 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drmingle/8ff59804761a44c531554f1557694a3b to your computer and use it in GitHub Desktop.
Save drmingle/8ff59804761a44c531554f1557694a3b to your computer and use it in GitHub Desktop.
title author date
Applying Functions To List Items
Damian Mingle
05/05/2018

Create a list of philosophers

philosopherNames = ['Aristotle', 'Plato', 'Socrates', 'Rene Descartes', 'Albert Camus']

For Loop Example

Create a for loop to go through the list and capitalizes each item

# create an object to hold loop results
philosopherNamesCapitalized_loop = []

# for every item in philosopherNames
for i in philosopherNames:
    # capitalize the item and add it to philosopherNamesCapitalized_loop
    philosopherNamesCapitalized_loop.append(i.upper())
    
# View all results
philosopherNamesCapitalized_loop
['ARISTOTLE', 'PLATO', 'SOCRATES', 'RENE DESCARTES', 'ALBERT CAMUS']

Map() Example

Create a lambda function that capitalizes x

capitalizeThis = lambda x: x.upper()

Map the capitalizeThis function to philosopherNames, convert the map into a list, and view the variable

philosopherNamesCapitalized_map = list(map(capitalizer, philosopherNames))
philosopherNamesCapitalized_map
['ARISTOTLE', 'PLATO', 'SOCRATES', 'RENE DESCARTES', 'ALBERT CAMUS']

List Comprehension Example

Apply the expression x.upper to each item in the list called philosopher names.

philosopherNamesCapitalized_lc = [x.upper() for x in philosopherNames]
philosopherNamesCapitalized_lc
['ARISTOTLE', 'PLATO', 'SOCRATES', 'RENE DESCARTES', 'ALBERT CAMUS']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment