basic_python/list_tuples.rst
changeset 20 20425ae92f41
parent 12 ea1bc776f495
child 46 b4d0089294b9
equal deleted inserted replaced
19:0fd0dcd7ba77 20:20425ae92f41
     1 Lists and Tuples
     1 Lists and Tuples
     2 ================
     2 ================
       
     3 
       
     4 Lists
       
     5 -----
     3 
     6 
     4 Python provides an intuitive way to represent a group items, called *Lists*. The
     7 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
     8 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 square
     9 type. A *List* is represented as a list of comma-sepated elements with square
     7 brackets around them::
    10 brackets around them::
    10   >>> a
    13   >>> a
    11   [10, 'Python programming', 20.3523, 23, 3534534L]
    14   [10, 'Python programming', 20.3523, 23, 3534534L]
    12 
    15 
    13 
    16 
    14 Common List Operations
    17 Common List Operations
    15 ----------------------
    18 ~~~~~~~~~~~~~~~~~~~~~~
    16 
    19 
    17 
    20 The following are some of the most commonly used operations on *Lists*.
       
    21 
       
    22 
       
    23 ~~~~~~~~
    18 Indexing
    24 Indexing
    19 ~~~~~~~~
    25 ~~~~~~~~
    20 
    26 
    21 Individual elements of a *List* can be accessed using an index to the element.
    27 Individual elements of a *List* can be accessed using an index to the element.
    22 The indices start at 0. One can also access the elements of the *List* in reverse
    28 The indices start at 0. One can also access the elements of the *List* in reverse
    29 
    35 
    30 It is important to note here that the last element of the *List* has an index of
    36 It is important to note here that the last element of the *List* has an index of
    31 -1.
    37 -1.
    32 
    38 
    33 
    39 
       
    40 ~~~~~~~~~~~~~
    34 Concatenating
    41 Concatenating
    35 ~~~~~~~~~~~~~
    42 ~~~~~~~~~~~~~
    36 
    43 
    37 Two or more *Lists* can be concatenated using the + operator::
    44 Two or more *Lists* can be concatenated using the + operator::
    38 
    45 
    40   [10, 'Python programming', 20.3523, 'foo', 12, 23.3432, 54]
    47   [10, 'Python programming', 20.3523, 'foo', 12, 23.3432, 54]
    41   >>> [54, 75, 23] + ['write', 67, 'read']
    48   >>> [54, 75, 23] + ['write', 67, 'read']
    42   [54, 75, 23, 'write', 67, 'read']
    49   [54, 75, 23, 'write', 67, 'read']
    43   
    50   
    44 
    51 
       
    52 ~~~~~~~
    45 Slicing
    53 Slicing
    46 ~~~~~~~
    54 ~~~~~~~
    47 
    55 
    48 A *List* can be sliced off to contain a subset of elements of the *List*. Slicing
    56 A *List* can be sliced off to contain a subset of elements of the *List*. Slicing
    49 can be done by using two indices separated by a colon, where the first index is
    57 can be done by using two indices separated by a colon, where the first index is
    86   [4, 6, 8]
    94   [4, 6, 8]
    87   >>> num[::4]
    95   >>> num[::4]
    88   [1, 5, 9]
    96   [1, 5, 9]
    89 
    97 
    90 
    98 
       
    99 ~~~~~~~~~~~~~~
    91 Multiplication
   100 Multiplication
    92 ~~~~~~~~~~~~~~
   101 ~~~~~~~~~~~~~~
       
   102 
    93 
   103 
    94 A *List* can be multiplied with an integer to repeat itself::
   104 A *List* can be multiplied with an integer to repeat itself::
    95 
   105 
    96   >>> [20] * 5
   106   >>> [20] * 5
    97   [20, 20, 20, 20, 20]
   107   [20, 20, 20, 20, 20]
    98   >>> [42, 'Python', 54] * 3
   108   >>> [42, 'Python', 54] * 3
    99   [42, 'Python', 54, 42, 'Python', 54, 42, 'Python', 54]
   109   [42, 'Python', 54, 42, 'Python', 54, 42, 'Python', 54]
   100 
   110 
   101 
   111 
       
   112 ~~~~~~~~~~
   102 Membership
   113 Membership
   103 ~~~~~~~~~~
   114 ~~~~~~~~~~
   104 
   115 
   105 **in** operator is used to find whether an element is part of the *List*. It
   116 **in** operator is used to find whether an element is part of the *List*. It
   106 returns **True** if the element is present in the *List* or **False** if it is not 
   117 returns **True** if the element is present in the *List* or **False** if it is not 
   112   True
   123   True
   113   >>> 'Adam' in names
   124   >>> 'Adam' in names
   114   False
   125   False
   115 
   126 
   116 
   127 
       
   128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
   117 Length, Maximum and Minimum
   129 Length, Maximum and Minimum
   118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
   130 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
   119 
   131 
   120 Length of a *List* can be found out using the len function. The max function
   132 Length of a *List* can be found out using the len function. The max function
   121 returns the element with the largest value and the min function returns the 
   133 returns the element with the largest value and the min function returns the 
   128   67
   140   67
   129   >>> min(num)
   141   >>> min(num)
   130   1
   142   1
   131 
   143 
   132 
   144 
       
   145 ~~~~~~~~~~~~~~~~~
   133 Changing Elements
   146 Changing Elements
   134 ~~~~~~~~~~~~~~~~~
   147 ~~~~~~~~~~~~~~~~~
   135 
   148 
   136 Unlike Strings *Lists* are mutable, i.e. elements of a *List* can be manipulated::
   149 Unlike Strings *Lists* are mutable, i.e. elements of a *List* can be manipulated::
   137 
   150 
   139   >>> a[2] = 9
   152   >>> a[2] = 9
   140   >>> a
   153   >>> a
   141   [1, 3, 9, 7]
   154   [1, 3, 9, 7]
   142 
   155 
   143 
   156 
       
   157 ~~~~~~~~~~~~~~~~~
   144 Deleting Elements
   158 Deleting Elements
   145 ~~~~~~~~~~~~~~~~~
   159 ~~~~~~~~~~~~~~~~~
   146 
   160 
   147 An element or a slice of a *List* can be deleted by using the **del** statement::
   161 An element or a slice of a *List* can be deleted by using the **del** statement::
   148 
   162 
   153   >>> del a[1]
   167   >>> del a[1]
   154   >>> a
   168   >>> a
   155   [1, 5, 7]
   169   [1, 5, 7]
   156 
   170 
   157 
   171 
       
   172 ~~~~~~~~~~~~~~~~
   158 Assign to Slices
   173 Assign to Slices
   159 ~~~~~~~~~~~~~~~~
   174 ~~~~~~~~~~~~~~~~
   160 
   175 
   161 In the same way, values can be assigned to individual elements of the *List*, 
   176 In the same way, values can be assigned to individual elements of the *List*, 
   162 a *List* of elements can be assigned to a slice::
   177 a *List* of elements can be assigned to a slice::
   175 example insert elements or a list of elements into a *List* and the last example
   190 example insert elements or a list of elements into a *List* and the last example
   176 deletes a list of elements from the *List*.
   191 deletes a list of elements from the *List*.
   177 
   192 
   178 
   193 
   179 None, Empty Lists, and Initialization
   194 None, Empty Lists, and Initialization
   180 -------------------------------------
   195 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   181 
   196 
   182 An *Empty List* is a *List* with no elements and is simply represented as
   197 An *Empty List* is a *List* with no elements and is simply represented as
   183 []. A *None List* is one with all elements in it being **None**. It serves
   198 []. A *None List* is one with all elements in it being **None**. It serves
   184 the purpose having a container list of some fixed number of elements with
   199 the purpose having a container list of some fixed number of elements with
   185 no value::
   200 no value::
   191   >>> n
   206   >>> n
   192   [None, None, None, None, None, None, None, None, None, None]
   207   [None, None, None, None, None, None, None, None, None, None]
   193 
   208 
   194 
   209 
   195 Nested Lists
   210 Nested Lists
   196 ------------
   211 ~~~~~~~~~~~~
   197 
   212 
   198 As mentioned earlier, a List can contain elements of any data type. This also
   213 As mentioned earlier, a List can contain elements of any data type. This also
   199 implies a *List* can have a *Lists* themselves as its elements. These are 
   214 implies a *List* can have a *Lists* themselves as its elements. These are 
   200 called as *Nested Lists*. There is no limit on the depth of the *Nested Lists*::
   215 called as *Nested Lists*. There is no limit on the depth of the *Nested Lists*::
   201 
   216 
   202   >>> a = [1, [1, 2, 3], 3, [1, [1, 2, 3]], 7]
   217   >>> a = [1, [1, 2, 3], 3, [1, [1, 2, 3]], 7]
   203 
   218 
   204 
   219 
   205 List Methods
   220 List Methods
   206 ------------
   221 ~~~~~~~~~~~~
   207 
   222 
   208 A method is a function that is coupled to an object. More about objects
   223 A method is a function that is coupled to an object. More about objects
   209 and its methods are discussed in Advanced Python module. In general, a
   224 and its methods are discussed in Advanced Python module. In general, a
   210 method is called like::
   225 method is called like::
   211 
   226 
   218 the *List* methods.
   233 the *List* methods.
   219 
   234 
   220 Some of the most commonly used *List* methods are as follows:
   235 Some of the most commonly used *List* methods are as follows:
   221 
   236 
   222 
   237 
       
   238 ~~~~~~
   223 append
   239 append
   224 ~~~~~~
   240 ~~~~~~
   225 
   241 
   226 The *append* method is used to append an object at the end of the list::
   242 The *append* method is used to append an object at the end of the list::
   227 
   243 
   231   [2, 3, 5, 7]
   247   [2, 3, 5, 7]
   232 
   248 
   233 It is important to note that append changes the *List* in-place.
   249 It is important to note that append changes the *List* in-place.
   234 
   250 
   235 
   251 
       
   252 ~~~~~
   236 count
   253 count
   237 ~~~~~
   254 ~~~~~
   238 
   255 
   239 The *count* method returns the number of occurences of a particular element
   256 The *count* method returns the number of occurences of a particular element
   240 in a list::
   257 in a list::
   244   >>> tlst = ['Python', 'is', 'a', 'beautiful', 'language']
   261   >>> tlst = ['Python', 'is', 'a', 'beautiful', 'language']
   245   >>> tlst.count('Python')
   262   >>> tlst.count('Python')
   246   1
   263   1
   247 
   264 
   248 
   265 
       
   266 ~~~~~~
   249 extend
   267 extend
   250 ~~~~~~
   268 ~~~~~~
   251 
   269 
   252 The *extend* method extends the list on which it is called by the list supplied
   270 The *extend* method extends the list on which it is called by the list supplied
   253 as argument to it::
   271 as argument to it::
   259 
   277 
   260 This is an in-place method. This method is equivalent to using the + operator, but
   278 This is an in-place method. This method is equivalent to using the + operator, but
   261 using the + operator returns a new list.
   279 using the + operator returns a new list.
   262 
   280 
   263 
   281 
       
   282 ~~~~~
   264 index
   283 index
   265 ~~~~~
   284 ~~~~~
   266 
   285 
   267 The *index* method returns the index position of the element in the list 
   286 The *index* method returns the index position of the element in the list 
   268 specified as argument::
   287 specified as argument::
   270   >>> a = [1, 2, 3, ,4, 5]
   289   >>> a = [1, 2, 3, ,4, 5]
   271   >>> a.index(4)
   290   >>> a.index(4)
   272   3
   291   3
   273 
   292 
   274 
   293 
       
   294 ~~~~~~
   275 insert
   295 insert
   276 ~~~~~~
   296 ~~~~~~
   277 
   297 
   278 The *insert* method is used to insert an element specified as the second 
   298 The *insert* method is used to insert an element specified as the second 
   279 argument to the list at the position specified by the first argument::
   299 argument to the list at the position specified by the first argument::
   284   ['Python', 'is', 'so', 'cool']
   304   ['Python', 'is', 'so', 'cool']
   285 
   305 
   286 The *insert* method changes the *List* in-place.
   306 The *insert* method changes the *List* in-place.
   287 
   307 
   288 
   308 
       
   309 ~~~
   289 pop
   310 pop
   290 ~~~
   311 ~~~
   291 
   312 
   292 The *pop* method removes an element from the list. The index position
   313 The *pop* method removes an element from the list. The index position
   293 of the element to be removed can be specified as an argument to the
   314 of the element to be removed can be specified as an argument to the
   302   3
   323   3
   303 
   324 
   304 The *pop* method changes the *List* in-place.
   325 The *pop* method changes the *List* in-place.
   305 
   326 
   306 
   327 
       
   328 ~~~~~~
   307 remove
   329 remove
   308 ~~~~~~
   330 ~~~~~~
   309 
   331 
   310 The *remove* method removes the first occurence of an element supplied as a
   332 The *remove* method removes the first occurence of an element supplied as a
   311 parameter::
   333 parameter::
   314   >>> a.remove(2)
   336   >>> a.remove(2)
   315   >>> a
   337   >>> a
   316   [1, 3, 4, 2, 5, 2]
   338   [1, 3, 4, 2, 5, 2]
   317 
   339 
   318 
   340 
       
   341 ~~~~~~~
   319 reverse
   342 reverse
   320 ~~~~~~~
   343 ~~~~~~~
   321 
   344 
   322 The *reverse* method reverses elements in the list. It is important to note
   345 The *reverse* method reverses elements in the list. It is important to note
   323 here that *reverse* method changes the list in-place and doesn't return any
   346 here that *reverse* method changes the list in-place and doesn't return any
   327   >>> a.reverse()
   350   >>> a.reverse()
   328   >>> a
   351   >>> a
   329   ['tim', 'alex', 'guido']
   352   ['tim', 'alex', 'guido']
   330 
   353 
   331 
   354 
       
   355 ~~~~
   332 sort
   356 sort
   333 ~~~~
   357 ~~~~
   334 
   358 
   335 The *sort* method is used to sort the elements of the list. The *sort* method
   359 The *sort* method is used to sort the elements of the list. The *sort* method
   336 also sorts in-place and does not return anything::
   360 also sorts in-place and does not return anything::
   351   >>> a
   375   >>> a
   352   [5, 1, 3, 7, 4]
   376   [5, 1, 3, 7, 4]
   353 
   377 
   354 
   378 
   355 List Comprehensions
   379 List Comprehensions
   356 -------------------
   380 ~~~~~~~~~~~~~~~~~~~
   357 
   381 
   358 List Comprehension is a convenvience utility provided by Python. It is a 
   382 List Comprehension is a convenvience utility provided by Python. It is a 
   359 syntatic sugar to create *Lists*. Using *List Comprehensions* one can create
   383 syntatic sugar to create *Lists*. Using *List Comprehensions* one can create
   360 *Lists* from other type of sequential data structures or other *Lists* itself.
   384 *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
   385 The syntax of *List Comprehensions* consists of a square brackets to indicate
   371 
   395 
   372 The syntax used here is very clear from the way it is written. It can be 
   396 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, 
   397 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."
   398 if remainder of x divided by 2 is 0, add x to the list."
   375 
   399 
       
   400 
       
   401 Tuples
       
   402 ------
       
   403 
       
   404 *Tuples* are sequences just like *Lists*, but they are immutable. In other
       
   405 words *Tuples* provides a way to represent a group of items, where the group
       
   406 of items cannot be changed in any way. The syntax of a *Tuple* is also very
       
   407 similar to *List*. A *Tuple* is represented with the list of items, called
       
   408 elements of the *Tuple* separated by comma, with the entire list being enclosed
       
   409 in parenthesis. It is not compulsory to use parenthesis around a *Tuple* but
       
   410 it may be necessary in some of the cases::
       
   411 
       
   412   >>> a = 1, 2, 3
       
   413   >>> a
       
   414   (1, 2, 3)
       
   415   >>> b = 1,
       
   416   >>> b
       
   417   (1,)
       
   418 
       
   419 It is interesting to note the second example. Just a value followed by a comma
       
   420 automatically makes that an element of a *Tuple* with only one element. It is
       
   421 also important to note that, irrespective of input having a parenthesis, the
       
   422 output always has a parenthesis.
       
   423 
       
   424 The first example is also known as *Tuple packing*, because values are being
       
   425 packed into a tuple. It is also possible to do *Tuple unpacking* which is more
       
   426 interesting. It is better to understand that by example. Say we have a 
       
   427 co-ordinate pair from which we need to separate x and y co-ordinates::
       
   428 
       
   429   >>> a = (1, 2)
       
   430   >>> x, y = a
       
   431   >>> x
       
   432   1
       
   433   >>> y
       
   434   2
       
   435 
       
   436 *Tuple unpacking* also has several other use-cases of which the most interesting
       
   437 one is to swap the values of two variables. Using programming languages like C
       
   438 would require anywhere around 10 lines of code and an extra temporary variable
       
   439 to do this (including all the #include stuff). Python does it in the most
       
   440 intuitive way in just one line. Say we want to swap the co-ordinates in the
       
   441 above example::
       
   442 
       
   443   >>> x, y = y, x
       
   444   >>> x
       
   445   2
       
   446   >>> y
       
   447   1
       
   448 
       
   449 Common Tuple Operations
       
   450 ~~~~~~~~~~~~~~~~~~~~~~~
       
   451 
       
   452 There is no need to introduce all the *Tuple* operations again, since *Tuples*
       
   453 support the following operations that *List* supports in exactly the same way:
       
   454 
       
   455   * Indexing
       
   456   * Concatenating
       
   457   * Slicing
       
   458   * Membership
       
   459   * Multiplication
       
   460   * Length, Maximum, Minimum
       
   461 
       
   462 The following examples illustrate the above operations::
       
   463 
       
   464   >>> a = (1, 2, 3, 4, 5, 6)
       
   465   >>> a[5]
       
   466   6
       
   467   >>> b = (7, 8, 9)
       
   468   >>> a + b
       
   469   (1, 2, 3, 4, 5, 6, 7, 8, 9)
       
   470   >>> a[3:5]
       
   471   (4, 5)
       
   472   >>> 5 in a
       
   473   True
       
   474   >>> c = (1,)
       
   475   >>> c * 5
       
   476   (1, 1, 1, 1, 1)
       
   477   >>> len(a)
       
   478   6
       
   479   >>> max(a)
       
   480   6
       
   481   >>> min(a)
       
   482   1
       
   483 
       
   484 However the following *List* operations are not supported by *Tuples* because
       
   485 *Tuples* cannot be changed once they are created:
       
   486 
       
   487   * Changing elements
       
   488   * Deleting elements
       
   489   * Assigning to slices
       
   490 
       
   491 Similarity to *Lists* leads to the questions like, why not *Lists* only? Why do
       
   492 we even want *Tuples*? Can we do the same with *Lists*? And the answer is **Yes**
       
   493 we can do it, but *Tuples* are helpful at times, like we can return Tuples from
       
   494 functions. They are also returned by some built-in functions and methods. And
       
   495 also there are some use cases like co-ordinate among other things. So *Tuples*
       
   496 are helpful.
       
   497 
       
   498 
       
   499 Conclusion
       
   500 ----------
       
   501 
       
   502 This section on *Lists* and *Tuples* introduces almost all the necessary 
       
   503 machinary required to work on *Lists* and *Tuples*. Topics like how to
       
   504 iterate through these data structures will be introduced in the later
       
   505 sections.
       
   506