basic_python/list_tuples.rst
changeset 6 6921d82a80db
parent 5 dbc118349011
child 11 edd18b1f5cb8
equal deleted inserted replaced
5:dbc118349011 6:6921d82a80db
     1 Lists and Tuples
     1 Lists and Tuples
     2 ================
     2 ================
     3 
     3 
     4 Python provides an intuitive way to represent a group items, called *Lists*. The
     4 Python provides an intuitive way to represent a group items, called *Lists*. The
     5 items of a *List* are called its elements. Unlike C/C++, elements can be of any
     5 items of a *List* are called its elements. Unlike C/C++, elements can be of any
     6 type. A *List* is represented as a list of comma-sepated elements with paren-
     6 type. A *List* is represented as a list of comma-sepated elements with square
     7 thesis around them::
     7 brackets around them::
     8 
     8 
     9   >>> a = [10, 'Python programming', 20.3523, 23, 3534534L]
     9   >>> a = [10, 'Python programming', 20.3523, 23, 3534534L]
    10   >>> a
    10   >>> a
    11   [10, 'Python programming', 20.3523, 23, 3534534L]
    11   [10, 'Python programming', 20.3523, 23, 3534534L]
    12 
    12 
   349   >>> b
   349   >>> b
   350   [1, 3, 4, 5, 7]
   350   [1, 3, 4, 5, 7]
   351   >>> a
   351   >>> a
   352   [5, 1, 3, 7, 4]
   352   [5, 1, 3, 7, 4]
   353 
   353 
       
   354 
       
   355 List Comprehensions
       
   356 -------------------
       
   357 
       
   358 List Comprehension is a convenvience utility provided by Python. It is a 
       
   359 syntatic sugar to create *Lists*. Using *List Comprehensions* one can create
       
   360 *Lists* from other type of sequential data structures or other *Lists* itself.
       
   361 The syntax of *List Comprehensions* consists of a square brackets to indicate
       
   362 the result is a *List* within which we include at least one **for** clause and
       
   363 multiple **if** clauses. It will be more clear with an example::
       
   364 
       
   365   >>> num = [1, 2, 3]
       
   366   >>> sq = [x*x for x in num]
       
   367   >>> sq
       
   368   [1, 4, 9]
       
   369   >>> all_num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
       
   370   >>> even = [x for x in all_num if x%2 == 0]
       
   371 
       
   372 The syntax used here is very clear from the way it is written. It can be 
       
   373 translated into english as, "for each element x in the list all_num, 
       
   374 if remainder of x divided by 2 is 0, add x to the list."
       
   375