Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.