Pythonic syntax is a syntax that uses the most efficient idioms for the small code patterns
There is always a better way to program while using python.I have been using python for some time now.The big mistake people do while starting with python is that thinking it a s a java alternative.As predominantly introduced to java or C++ earlier in life people use the same paradigm of programming while coding in python.This makes python code look ugly , run slower unthinkably large and very very slow.
List Comprehensions
List comprehensions are compact way to build a list in python.consider a program to generate all even numbers within say 10.The usual way of doin things is:
>>>numbers=range(10)
>>>size=len(numbers)
>>>evens=[]
>>>while i>>evens
[0,2,4,6,8]
But this style of coding in python does not harness the immense power the language offers.Consider how to do this with List comprehension:
>>>evens=[i for i in range(10) if i%2==0]
Iterators and Generators:
All looping in python is in turn implemented using the iterator protocol in python.An iterator class contains two methods namely:
next():The next method returns the next value in the class and on reaching the last value raises StopIteration Exception.
__iter__():This method just returns the iterator itself.
They are created with iter builtin function by the following way.
>>>iter_obj=iter(range(5))
>>>iter_obj.next()
0
Python generators:
To say simply a generator is method that has a yield statement.Rather than returning a single value(say the lines of a file )we generate a series of values using yield statement.
def countdown(n):
while n > 0:
yield n
n -= 1
>>> for i in countdown(5):
… print i,
…
5 4 3 2 1
>>>obj=countdown(10)
>>>obj
So creating an instance of countdown(remember functions are first class objects) will only create a generator object not execute the method.
>>>obj.next()
Counting down from n 10
10
Generators in real time can be constructed fairly simply by the following way:
>>>name=[“ashok”,”samrat”]
>>>capital=(n.capitalize() for n in name)
>>>capital
>>>capital.next()
‘Ashok’
This can be used to read very large files or fetch database records with fairly simpler and more beautifull syntax and is less memory intensive.