Sunday, 3 September 2017

Python Q and A

Function To Randomize The Items Of A List In-Place

Python has a built-in module called as . It exports a public method )> which can randomize any input sequence.

import random
list = [2, 18, 8, 4]
print "Prior Shuffling - 0", list
random.shuffle(list)
print "After Shuffling - 1", list
random.shuffle(list)
print "After Shuffling - 2", list
 

Best Way To Split A String In Python

test = "I am learning Python."
print test.split(" ") #['I', 'am', 'learning', 'Python.']
 

 What is the output of print list + tinylist * 2 if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] and tinylist = [123, 'john']?

It will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.2, 123, 'john', 123, 'john'].

What is the output of print tinytuple * 2 if tinytuple = (123, 'john')?

Output would be (123, 'john', 123, 'john')

Python String Into A List?

list("I am learning Python.")=> ['I', ' ', 'a', 'm', ' ', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', ' ', 'P', 'y', 't', 'h', 'o', 'n', '.']

Exception Handling In Python

There are following clauses available in Python language.
1. try-except-finally
2. try-except-else

The And Comprehensions?

comprehensions provide an easier way to create the corresponding object using the existing iterable. As per official Python documents, the list comprehensions are usually faster than the standard loops.

#Simple Iteration
item = []
for n in range(10):
    item.append(n*2)
print item #[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
 
#List Comprehension
 
#Dict Comprehension
item = {n: n*2 for n in range(10)}
print item #{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
 

 You Know To Copy An Object In Python?

Commonly, we use or to perform copy operation on objects.

But some objects are easier to copy. Like the dictionary objects provide a method.

 Though not all objects support these methods but most do.

item = {n: n*2 for n in range(10)}
newdict = item.copy()
print newdict
 

Code To Check Whether The Given Object Belongs To A Class Or Its Subclass?

def lookUp(obj):
    if isinstance(obj, Mailbox):
        print "Look for a mailbox"
    elif isinstance(obj, Document):
        print "Look for a document"
    else:
        print "Unidentified object"
 
 Python lambdas
lambda is just a fancy way of saying function. Other than its name, there is nothing obscure.
replace lambda by function in your mind:
>>> f = lambda x: x + 1
>>> f(3)
4
It just defines a function of x. Some other languages, like R, say it explicitly:
> f = function(x) { x + 1 }
> f(3)
4

Late Binding Closures

def create_multipliers():
    return [lambda x : i * x for i in range(5)]
 Above function can be covert as below
def create_multipliers():
    multipliers = []

    for i in range(5):
        def multiplier(x):
            return i * x
        multipliers.append(multiplier)

    return multipliers 
for multiplier in create_multipliers():
    print multiplier(2)  
A list containing five functions that each have their own closed-over i variable that multiplies their argument, producing:
0
2
4
6
8
 What Does Happen
8
8
8
8
8
Five functions are created; instead all of them just multiply x by 4.
 
 Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called.
 

 Solution of above problem is below

you can create a closure that binds immediately to its arguments by using a default arg like so:
def create_multipliers():
    return [lambda x, i=i : i * x for i in range(5)]

Bytecode (.pyc) Files Everywhere!

By default, when executing Python code from files, the Python interpreter will automatically write a bytecode version of that file to disk, e.g. module.pyc.
These .pyc files should not be checked into your source code repositories.
Theoretically, this behavior is on by default, for performance reasons. Without these bytecode files present, Python would re-generate the bytecode every time the file is loaded.

Disabling Bytecode (.pyc) Files

Luckily, the process of generating the bytecode is extremely fast, and isn’t something you need to worry about while developing your code.
Those files are annoying, so let’s get rid of them!
$ export PYTHONDONTWRITEBYTECODE=1

 

No comments:

Post a Comment