Pythonic Magic: List Comprehensions

Disclaimer: This will be the beginning of a series of articles, inside which I will select some of the features in python that I like the most and why I do like them, along with some description and usage of the feature at hand.

Disclaimer: I do not claim to be an expert in python (or any other language for that matter). Anything that follows is my own personal opinion, and may even be wrong, as it is dependent on my understanding on the matter. However I am doing my best to make sure that I do not include wrong information.

—————————————————————————————————————-

You may have heard that the Python programming language is easy to both learn and use. You should slap those that told you so, for blatantly lying to you. Python is not easy to learn. It is *very* easy. *Very very easy*. As a matter of fact it’s so easy that even babies could learn python.  Hyperbole, but you get the point.

I am not going to go to lengths as to why you should learn python. As a matter of fact, a google search can possibly give you many reasons to do so. However the ultimate reason for one to learn python, is to simply want to do so. Why you would want to do so, is an entirely different matter which I will not discuss here, or I will miss the original subject of this article. Which is: wait for it… List Comprehensions! Who could imagine!

Before I go on to explain what list comprehensions are, maybe I should give a description of what lists in python are. Lists are well…lists. Pretty surprising huh? No, on a more serious note, lists in python are a data structure, that acts like a container for any amount of objects, in a given order. If you already have been introduced to programming via another programming language, you may be able to think of the list as an array of objects, which has variable length. In fact Lists are much more powerful than that, following the tradition that Python follows, which is to ensure that you have all the tools that you may possibly need to work right out of the box. In fact, lists (and the other data structures that python provides by default, such dictionaries, sequences, tuples, etc) are so powerful and versatile, that 99% of the time, you will not need to use anything else than what Python already provides. Below is a demonstration of the lists in python.

>>> my_list = [3, 4, 5] # this creates a list with 3 integer objects
>>> my_list
[3, 4, 5]

>>> my_list = [] # this creates an empty list
>>> my_list
[]

>>> my_list.append(5) # this adds 5 to the list
>>> my_list
[5]

>>> my_list.insert(0,3) # this adds 3 in the first position of the list
>>> my_list
[3, 5] # python like many other languages is 0 indexed. This means that list indices begin with 0 instead of 1.

>>> my_list.remove(3) # nothing unexpected here
>>> my_list
[5]

>>> item = my_list.pop() # removes the object from the list, and returns it to be stored at item
>>> item
5

>>> my_list
[]

This pretty much sums the basic usage of Lists in python. I won’t go to any greater extend to because that would doesn’t concern this article. If you would like to read more about lists and their usage, I recommend that you study the official Python tutorials on Lists.

Now that we have talked about Lists, it’s time to talk about List Comprehensions. List Comprehensions are simply a sophisticated way to create Lists that have specific contents. If that doesn’t help you, maybe we should look at an example.

Let’s say we want to create a list of the even numbers in the range between 0 up to (but not including) 10. Normally you would do something like this:

>>> my_list = [] # constructing an empty list
>>> for number in range(10):
        if number % 2 == 0:
            my_list.append(number)
>>> my_list
[0, 2, 4, 6, 8]

List comprehensions allow you to do just the same thing, just times easier (and more sexy, by the way):

>>> even_nums = [x for x in range(10) if x % 2 == 0]
>>> even_nums
[0, 2, 4, 6, 8]

Holly floppy McBaggies. Did you see that? Human words fail to describe the Beauty and the Epic-ness in this.

You might be wondering now. How could I possibly use this to get the most out of my life  it? Well to be honest, there are many ways you could possibly use this feature. Yours trully uses List Comprehensions to create Lists out of  Strings (which are Immutable, that means they are unable to be changed. The reason is here.) to allow for easier manipulation of those. For example:

>>> name = 'fotis'

>>> name[1] = 'u'
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> name_list = [letter for letter in name] # creating a list out of name's characters
>>> name_list
['f', 'o', 't', 'i', 's']
>>> name_list[1] = 'u'

>>> name = ''.join(name_list)
>>> name
'futis'

As you can see we are talking about an extremely powerful feature, that one could use to create lists that have objects that are computed on the fly. As to the possible usage cases for this? Only your fantasy could possibly stop you from using it.

Advertisements

One thought on “Pythonic Magic: List Comprehensions

/comment

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