Creating a list from another list - list comprehension

Comprehension is a way to create a sequence from another sequence. For example, we can create a list from another list or tuple. Let's look at a list comprehension. Typically, a list comprehension involves the following features:

  • A sequence, say a list whose elements we are interested in
  • A variable representing the elements of the sequence
  • An output expression that is responsible for producing the output sequence using the elements of the input sequence
  • An optional predicate expression

Getting ready

Let's define a simple problem in order to understand all the different elements involved in comprehension. With an input list with positive and negative numbers, we need an output list that is the square of all the negative elements.

How to do it…

In the following script, we will show a simple example of list comprehension:

# 1.	Let us define a simple list with some positive and negative numbers.
a = [1,2,-1,-2,3,4,-3,-4]

# 2.	Now let us write our list comprehension.
# pow() a power function takes two input and
# its output is the first variable raised to the power of the second.
b = [pow(x,2) for x in a if x < 0]

# 3.	Finally let us see the output, i.e. the newly created list b.
print b

How it works…

This example is written in a way to explain the various components of comprehension. Let's look at step 2:

b = [pow(x,2) for x in a if x < 0]

This code is explained as follows:

  • Our input list is a and output list is b
  • We will use a variable x to represent each element in the list
  • The pow(x,2) is the output expression, which uses the elements in the input to produce the output list
  • Finally, if x < 0 is the predicate expression that controls which elements of the input list are used to produce the output list

There's more…

The comprehension syntax is exactly the same as a dictionary. A simple example will illustrate the following:

a = {'a':1,'b':2,'c':3}
b = {x:pow(y,2) for x,y in a.items()}
print b

In the preceding example, we created a new dictionary, b from the input dictionary, a. The output is as follows:

{'a': 1, 'c': 9, 'b': 4}

You can see that we retained the keys of the a dictionary, but now the new values are a square of the original values in a. A point to note is the use of curly bracelets instead of brackets during the comprehension.

We can do comprehension for tuples with a small trick. See the following example:

def process(x):
    if isinstance(x,str):
        return x.lower()
    elif isinstance(x,int):
        return x*x
    else:
        return -9

a = (1,2,-1,-2,'D',3,4,-3,'A')
b = tuple(process(x) for x in a )

print b

Instead of the pow() function, we used a new process function. I will leave it to you as an exercise to decipher what the process function does. Note that we followed the same syntax for a comprehension list; however, we used braces instead of brackets. The output of this program is as follows:

<generator object <genexpr> at 0x05E87D00>

Oops! We wanted a tuple but ended up with a generator (more on generators in the later sections). The right way to do it is as follows:

b = tuple(process(x) for x in a )

Now, the print b statement will produce the following output:

(1, 4, 1, 4, 'd', 9, 16, 9, 'a')

Python comprehension is based on the set builder notation:

http://en.wikipedia.org/wiki/Set-builder_notation

Itertools.dropwhile:

https://docs.python.org/2/library/itertools.html#itertools.dropwhile

With a predicate and sequence, dropwhile will return only those items in the sequence that satisfies the predicate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset