Top Ad unit 728 × 90

python tips and tricks

 In-place swapping of two numbers:

Python provides an intuitive way to do assignments and swapping in one line. please refer to the below example.

x ,   y = 10,  20
print (x  ,y)

x ,    y = y ,   x
print (x ,  y)

#1    (10 ,    20)
#2    ( 20 ,    10)

The assignment on the right seeds a new tuple. while the left one instantly unpacks that (unreferenced) tuple to the names <a>  and <b>.

Once the assignment is through, the tuple gets unreferenced and flagged for garbage collection. The swapping of variable also occurs at eventually.

Chaining of comparison operators:

Aggregation of comparison operators is another trick that can come handy at times.

n  =  10
result  = 1 < n < 20
print  ( result )

#  ture

result =  1  >  n  <  =  9
print ( result )

#  false

Use of ternary operators for conditional assignment:

Ternary operators are a shortcut for an if else statement and also known as conditional operators.

[on_true ]   if   [expression ]   else

here are a few example which you can use to make your code compact and concise. The below statement is doing the same what it is meant to i.e. "assign  10  to  if  y  is 9, otherwise assign  20 to x". We can thrugh extend the chaining of operators if required.

x  =  10  if  (y  = =  9)  else  20

likewise, we can do the same for class objects.

x  =  ( class A  if   y  = =  1   else  class B)

In the above example, class A  and class B  are two classes and one of the class are two classes and one of the class constructors would get called.

Below is one more example with a no. of conditions joining to evaluate the smallest number.

def     small ( a,   b ,   c )  :
 return  a  if   a  <  =  b   and  a  <  = c  e

print ( small ( 1 , 0 , 1 ))
print ( small ( 1 , 2 , 2 ))
print ( small ( 2 , 2 , 3 ))
print ( small ( 5 , 4 , 3 ))

# outpu
#0  #1  #2   #3
 
we can even use a ternary operators with the list comprehension.

[m**2  if  m > 10  else  m**4  for  m
# = >  [ 0 , 1 , 16 , 81 , 256 , 625 , 12]

Work with multi-line strings:

the basic approach is to use backslashes which derive itself from C language.

multistr  =  " select * from multi
where row_id  <  5"
print(multistr)

#select  *   from  multi_row where 

One more tick is to  use the triple-quotes.

multistr = """ select  * from  multi
where row_id < 5 "

#select  *  from multi_row
#where row_id < 5

The common issue with the above methods is the lack of proper indentation. If we try to indent, it'll insert whitespaces in the string.  So the final solution id to split the string into multi lines and enclose the entire sting in parenthesis.

multistr  = ( "select * from multi
"where row_id <4 "
"order  by age")
 print (multistr)

#select  * from multi_row  where

Storing element of a list into new variables:

We can use a list to initialize a number  of variables should not exceed the number of element in the list.

testLisr = [1, 2, 3 ]
x , y, z =  testList

print ( x , y , z )

#-> 1  2   3

Use the interactive "-" operator:

it's a useful feature which not many of us know.  In  the python console, whenever we test an expression or call a function, the result dispatches to a temporary name, _ (an underscore).

>>>  2  +  1
3
>>>  _
3
>>>   print  _
3

The "_" references to the output of the last executed expression.


Dictionary/ set comprehensions:

like we use list comprehensions, we can also use dictionary / set comprehensions. They are simple to used and just as effective. Here is an example.

testDict  =  { i:  i * for   i   in  x 
testset   = { i  *  2  for  i   in xrange

print (testset)
print(testDict)

#set [ 0 ,2, 4, 6, 8, 10, 12, 14, 16]
#(0 : 0, 1:1 , 2:4, 3:9. 4:16}

Note:- There is only a difference of <:> in the two statement s. Also, to run the above code in python 3, replace <xrange> with<range>

Debugging scripts:

we can set breakpoints in our python script with the help of the <pdb> module. please follow the below example.

import pdb
pdb. set_trace()

we can specify <pdb .set_trsce()> anywhere in the script and set a breakpoint there. it's extremely convenient.

Set file sharing:

Python allows running  an HTTP server which you can use to share files from the server root directory. below are the comms=ands to start the server.

# Python 2

python  -m  Simple HTTP Server

#Python 3

python   -m http. server

Above commands would start a server on the default port i.e. 8000. You can also use a custom port by passing it as the last argument to the above commands.

Inspect an object in Pythin:

we can inspect objects in python by calling the dir() method. Here is a simple example.

test  =  [ 1,  3.   5.  7]
print ( dir(test)  )
[ ' _ _ add _ _ ' , ' _ _ class _ _' , ' _ _ con

Simplify if statement:

To verify multiple values, we can do in the following manner.

if  m  in [1  , 3 ,  5  ,  7  ]

instead of:

if  m = =1  or m = =3 or m==5 or m==7

Alternatively, we can use '{1,3,5,7}' instead of '[1,3,5,7]' for 'in' operator because 'set' can access each element by O(1).














python tips and tricks Reviewed by For Learnig on May 18, 2023 Rating: 5

No comments:

If you have any doubts, please tell me know

Contact Form

Name

Email *

Message *

Powered by Blogger.