Python Data Structures & Iterators - abhisheksura/Python GitHub Wiki


List, Tuples & Sets

A List is a data structure in Python which is changeable or mutable ordered sequence of elements.

new_list = []
my_list = [5, 13, "TERER", (43, 123)]

A tuple is data structure used to store the elements and is immutable.

new_tuple = ()
my_tuple = ('Answer', 656, 'Bharat')

A Set is an unordered datastructure where sequence is not maintained and is stores only distinct elements

new_set = set()
my_set = {"Ganesh", 94, "Ram", 94}

It will display the output as

my_set
{94, "Ganesh","Ram"}

Dictionaries


Comprehensions


Decorators

A decorator is a special kind of function that either takes a function/class as an argument, adds some functionality and returns a functionwithout altering the source code of the original function.

The @ symbol is just syntactic sugar that allows you to decorate something in a way that's easy to read

It takes one function makes some necessary changes(decorate it) and return the same function with decorations like html, formatting etc

def decorator_function(original_function):
    def wrapper_function():
        print "<font color ='greeen'>"
        return original_function()
    return wrapper_function

def display():
    print "Display Function"
    
decorated_display = decorator_function(display)

decorated_display()

OR

@decorator_function
display()

Iterators

Iterable - Anything which you can loop over is iterable. Eg: List For an object to be iterable it should have iter() method

Iterator- Iterator is simply an object which can return data one at a time while iterating over it. For an object to be iterator it should have 2 methods

  • iter
  • next

Use Cases - Used for large sets of data to save the resources by calling one element at a time.

Generally iterators are implemented in python using generators.


For loop internally creates an iterator object and iterates using next until StopIterator exception is occured

For loop internally uses while loop


Generators

A generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data.

Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed)

def  square(nums):
    for i in nums:
         yield(i*i)

mynums = square([1,2,3,4]
next(mynums)
1
next(mynums)
4
next(mynums)
9