Chapter 6

At the end of Chapter 5 I gave you the task of modifying the print_my_list function so that it prints lists in uppercase.

A quick Google should have led you to the upper function in the Python docs, and your modified script should look like this:

def print_in_uppercase(my_list):
    for item in my_list:
        print item.upper()


def main():
    with open('data.txt') as f:
        my_temporary_list = f.readlines()
    
    my_list = []
    for item in my_temporary_list:
        my_list.append(item.strip())

    print_in_uppercase(my_list)


if __name__ == '__main__':
    main()

That's Not Very Pythonic

What does that even mean??

All languages have natural ways to express concepts. We call these idioms.

To be Pythonic, we should use the idioms of Python. This will help other Python programmers quickly recognise our intentions whilst reading our code.

The way we have constructed my_list is not the natural way other Python programmers would do this.

Its not even very efficient.

List Comprehensions

List comprehensions are awesome. They are terse, elegant, and efficient.

Lets see the above example using a list comprehension.

def print_in_uppercase(my_list):
    for item in my_list:
      print item.upper()


def main():
    with open('data.txt') as f:
      my_temporary_list = f.readlines()
 
    #my_list = []
    #for item in my_temporary_list:
    #    my_list.append(item.strip())
 
    my_list = [item.strip() for item in my_temporary_list]
 
    print_in_uppercase(my_list)


if __name__ == '__main__':
    main()


I've commented out the lines the list comprehension replaces. 

As you can see, a list comprehension looks a bit like an inline for loop. I'd suggest reading from right to left here.

Loop through an existing list/collection/iterable:

for item in my_temporary_list

and do something to the item, before appending it to my_list.

item.strip()

The Final Script

You might have noticed that we have an unnecessary step in this script.

f.readlines() returns a list, so couldn't we just iterate over that in our list comprehension? (and get rid of my_temporary_list)

Making this change, and removing the commented-out code, gives us the following:

def print_in_uppercase(my_list):
    for item in my_list:
        print item.upper()


def main():
    with open('data.txt') as f:
        my_list = [item.strip() for item in f.readlines()]

    print_in_uppercase(my_list)


if __name__ == '__main__':
    main()


Go Do Something

Update the script to print list items (in uppercase) that are less than 5 characters long 

Please Share

If you found this useful, please share with friends.

comments powered by Disqus

Subscribe