Python syntax can be a whole lot simpler, if one tries to make his code more “Pythhonic”, i.e. use the features in Python to make elegant and easy to debug code.
1. LIST COMPREHENSION:
Let us say i ant to build a list of all odd numbers between 235 and 500.
odds = [i for i in range(235,501) if i % 2 != 0]
If I want to make a list of all names from an array(students) where student names > 5
names = [student for student in students if len(student) > 5]
Lets have a sequence
animals = [“cat”,”dog”,”mouse”]
Using enumerate we can get the index number and the element in the list
for i,animal in enumerate(animals): print ‘%d->%s’%(i,animal)
The enumerate can be compared to an interator. An iterator is a container object that implements the iterator protocol and has 2 methods:
next, returns the next item of the container
It returns a StopIteration exception when you move to the last element of the iterator container and do a next()