diff options
author | Madhusudan.C.S | 2009-08-20 20:26:21 +0530 |
---|---|---|
committer | Madhusudan.C.S | 2009-08-20 20:26:21 +0530 |
commit | 666535b5623b34e3519d072a02710fc264f84bc3 (patch) | |
tree | 70b4565005a344d589309b153e6a2e34932d3579 | |
parent | 369bb6bb1a828795ae5f54c9353555faadabbc0c (diff) | |
download | sees-666535b5623b34e3519d072a02710fc264f84bc3.tar.gz sees-666535b5623b34e3519d072a02710fc264f84bc3.tar.bz2 sees-666535b5623b34e3519d072a02710fc264f84bc3.zip |
Added a subsection on List Comprehension.
-rw-r--r-- | basic_python/list_tuples.rst | 26 |
1 files changed, 24 insertions, 2 deletions
diff --git a/basic_python/list_tuples.rst b/basic_python/list_tuples.rst index 6ff3595..14eff77 100644 --- a/basic_python/list_tuples.rst +++ b/basic_python/list_tuples.rst @@ -3,8 +3,8 @@ Lists and Tuples Python provides an intuitive way to represent a group items, called *Lists*. The items of a *List* are called its elements. Unlike C/C++, elements can be of any -type. A *List* is represented as a list of comma-sepated elements with paren- -thesis around them:: +type. A *List* is represented as a list of comma-sepated elements with square +brackets around them:: >>> a = [10, 'Python programming', 20.3523, 23, 3534534L] >>> a @@ -351,3 +351,25 @@ a sorted copy of the list. However the original list is left intact:: >>> a [5, 1, 3, 7, 4] + +List Comprehensions +------------------- + +List Comprehension is a convenvience utility provided by Python. It is a +syntatic sugar to create *Lists*. Using *List Comprehensions* one can create +*Lists* from other type of sequential data structures or other *Lists* itself. +The syntax of *List Comprehensions* consists of a square brackets to indicate +the result is a *List* within which we include at least one **for** clause and +multiple **if** clauses. It will be more clear with an example:: + + >>> num = [1, 2, 3] + >>> sq = [x*x for x in num] + >>> sq + [1, 4, 9] + >>> all_num = [1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> even = [x for x in all_num if x%2 == 0] + +The syntax used here is very clear from the way it is written. It can be +translated into english as, "for each element x in the list all_num, +if remainder of x divided by 2 is 0, add x to the list." + |