Python has a really cool feature known as comprehensions.  Below are a few examples of how this might work with lists.  They can also be implemented for dictionaries as well. 

     Say we want to create a list of characters that are part of a string containing a phrase.  Traditionally, we would approach that problem like this:

characters = []
phrase = “Python 3!”
for character in phrase:
    characters.append(character)
print(characters)

But with list comprehension, it can be reduced to this:

characters = [character for character in phrase]
print(characters)

Output is the same for both:

[‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘ ‘, ‘3’, ‘!’]
[‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘ ‘, ‘3’, ‘!’]

     To help remember how to implement a list comprehension, always think “[new_item for item in list]”.  But we can also have a condition with a list comprehension.  Lets say we want to convert names to all upper case, but only if they have more than 4 characters in them.  Below is how to accomplish that with a list comprehension.

names = [“Bill”, “Maria”, “Christopher”, “Sam”]
new_names = [name.upper() for name in names if len(name) > 4]
print(new_names)

Output:

[‘MARIA’, ‘CHRISTOPHER’]

 

Leave a Reply

Your email address will not be published. Required fields are marked *