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 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:
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.
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.
while n > 0:
n -= 1
>>> for i in countdown(5):
… print i,
5 4 3 2 1
So creating an instance of countdown(remember functions are first class objects) will only create a generator object not execute the method.
Counting down from n 10
Generators in real time can be constructed fairly simply by the following way:
>>>capital=(n.capitalize() for n in name)
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.