# my net house

WAHEGURU….!

## Python and my fav parts

September 1, 2016

Posted by on In this Post one can get head-start knowledge about basic but bit advanced corners of Python programming which can lead to beautiful code-base and title for Python Ninja in terms of experience.

1. List comprehensions

2. Generator Expressions

3. Generator function

**List comprehensions:** Which are basically iteration over list

Earlier approach:

p = [1,2,3,4,5]

In [4]: for i in range(len(p)):

p[i]+=10

In [5]: p

out[5]: [11, 22, 13, 14, 15]

Using List comprehensions we can provide much better code:

p = [1,2,3,4,5]

In [7]: p = [i+10 for i in p] # THis is list comprehensions

In [8]: p

Out[8]: [11, 12, 13, 14, 15]

Generator Expressions:

One potential downside of using a list comprehension is that it might

produce a large result if the original input is large. If this is a concern,

you can use generator expressions to produce the filtered values iteratively.

for example if list input is quite big Generator Expression is Amazing:

In [37]: p = (i for i in xrange(10000))

in[38]: p

Out[38]: at 0x7ff16e47b0a0>

Here we got the generator object, now we can use it as we want:

We can also use generator Expression as argument:

In [49]: p = (i for i in xrange(10000)) # remember we used xrange()

In [49]: p = list(p)

In [50]: s = sum(i*i for i in p)

In [51]: s

Out[51]: 333283335000

In [52]: s = sum(i+10 for i in p)

In [53]: s

Out[53]: 50095000

This stuff is super fast.

now using the generator expression convert tuple into CSV file:

In [54]: s = ('ACME', 50, 123.45)

In [55]: print(','.join(str(x) for x in s))

ACME,50,123.45

So from all the above discussion we are now clear of one thing that we should

use Generator expressions as much as you know.

**Generator Functions:**

Now any function which contains “yield” function. that is generator function.

there are many few examples I would Like to share here:

In [21]: def hello(item):

h = item*3

yield h

In [22]: for i in hello(item=’iamamazing’):

print i

iamamazingiamamazingiamamazing

so now above it generator function as we are learning about it.

Then what is practical use of this thing? Generator functions are mostly fast in terms of text processing before Going further I need to see how Generators are very helpful in

data-processing, Data Flow , Big data or any other kind of Stuff.