Pages

Saturday, December 26, 2015

Python List Comprehensions

Python does provide a Concept called “list Comprehension”. This can be sued in constructing list in a very easy and natural way.

It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. One important thing to remember is that
list comprehension always returns a result list.

The basic Syntax of the List comprehension starts with a '[' and ']'.
The syntax may look like this
[ expression for item in list if conditional ]

Which is equivalent to

for item in list:
    if conditional:
        expression
 
The most common ways of defining list are,
S = {x² : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2¹²)

The same thing can be written in Python as,
>>> S = [x**2 for x in range(10)]
>>> V = [2**i for i in range(13)]

A basic example of list Comprehension  can look like this,

>>> words = "the quick brown fox jumps over the laszy dog".split()
>>> print words
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'laszy', 'dog']

>>> stuff=  [[ w.upper(),w.lower(),len(w)] for w in words]
>>> print stuff
[['THE', 'the', 3], ['QUICK', 'quick', 5], ['BROWN', 'brown', 5], ['FOX', 'fox', 3], ['JUMPS', 'jumps', 5], ['OVER', 'over', 4], ['THE', 'the', 3], ['LASZY', 'laszy', 5], ['DOG', 'dog', 3]]

We can use other ways by using Maps and lambda but list comprehension is preferable because this is more efficient and easier to read, most of the time.

Another simple example would be to consider a case for generating Square number for a range of 10. This can be done by using a list and a for loop

>>> squ = []
>>> for x in range(10):
...     squ.append(x*x)
...
>>> print squ
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The same above things can be done by using the list comprehension in single like as,

>>> squ = [ x*2 for x in range(10)]
>>> print squ
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

List comprehension also allows us to use the decision making in that syntax as

>>> string = "hello 1world 2 3"
>>> number =[ x for x in string if x.isdigit()]
>>> print number
['1', '2', '3']

Or we can use with the file handling as,

fh = open("test.txt", "r")
result = [i for i in fh if "line3" in i]
print result


Hope this helps you with the basic understating of the List comprehensions in Python

No comments :

Post a Comment