Python – nice feature #2

Python offers some very nice language features for dealing with sequence data types.
A list is a type of sequence, and from a ColdFusion background lists are a familiar data type. List items will be of the same type and are mutable meaning they can be changed in place. Here’s a list, printed:

my_list = [1, 2, 3]
print "my_list:", my_list
# my_list: [1, 2, 3]

So the good stuff: you can actually loop over and change lists in a very succinct way in Python using list comprehensions. They work like this:

    # Create a list
    my_list = [1, 2, 3]
    print "my_list:", my_list

    # Create a new list from this list using a list comprehension
    new_list = [i*2 for i in my_list]
    print "new_list:", new_list

Just like that I have doubled the value of every item in the list! So the trick is the use of a standard Python loop:

    for i in my_list

But in instead of doing the processing after the for loop on the next line, instead we add the statements before the for, and then use the [] syntax to return a new list, like so:

    # Multiply every item in the list by 2
    new_list = [i*2 for i in my_list]

And as a bonus you can then add an if statement to so the transformation is only carried out on list items that meet that criteria, for example:

    my_list = [1, 2, 3]
    # Multiply every item in the list by 3 if list item is a multiple of 3
    new_list = [i*3 for i in my_list if i % 3 == 0]

This only return one item in the list ([9]).

This is a really clear way of doing operations on lists, and a really nice Python feature.

Advertisements
This entry was posted in regular and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s