Python - Itertools Part 1

Today I am going to explain my understanding on some of the amazing functions available in python's itertools module. These too are very essential functions, and a clear understanding of these methods would help one in becoming a better python programmer. All these methods will return an iterable object as response.

  1. count:
  2. A count method is similar to range and xrange methods,except the fact that it does'nt need a stop variable. The implementation is shown below,

    
                 def count(start=0, step=1):
                  # count(10) --> 10 11 12 13 14 ...
                  # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
                  n = start
                  while True:
                   yield n
                   n += step
                  >>> li=[1,2,3]
                  >>> map(lambda x:x**2,li)
                  [1, 4, 9]
                
  3. reduce:
  4. A cycle method loops over the given list of items again and again.

    
               
                def cycle(iterable):
                 # cycle('ABCD') --> A B C D A B C D A B C D ...
                 saved = []
                 for element in iterable:
                  yield element
                  saved.append(element)
                 while saved:
                  for element in saved:
                     yield element
                   
  5. dropwhile:
  6. Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element.

    
                     for j in i.dropwhile(lambda x: x<5, [1,4,6,4,1]):
                         print j
               
                6
                4
                1
               
    Here, 1,4 fails the test and once 6 passes,all other elements are returned.
  7. ifilter:
  8. this method filters the data such that the data that pass validation are returned as result.

    
                >>> for j in i.ifilter(lambda x: x%2, range(10)):
                 j
               
               
                1
                3
                5
                7
                9
               

Leave a comment