Python @ DjangoSpin

50+ Tips & Tricks for Python Developers

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 31 minutes

Page #2


Equality test (==) and Assignment operation (=)

Beginners often get confused between these two operators. The single equal operator ( = ) is used for assigning a value to a variable, whereas the double equal operator ( == ) is used to check the value held by the variable.

>>> a = 10
>>> a == 10
True
>>> a == 20
False

An enhanced interpreter: IPython

IPython is a third-party interactive interpreter which has an array of features lacking in the original interactive interpreter of Python. It provides a browser-based notebook with support for rich media, code introspection, history, re-usability of sessions, inline plots, tab completion, re-executable statements, scrollable output among other things. It supports interactive data visualization and non-blocking use of GUI toolkits. These interpreter notebooks can be easily embedded into other projects.

For full list of features, visit IPython on The Cheese Shop. For its documentation, visit Jupyter Documentation. Project Jupyter is a spin-off project from IPython, announced in 2014. Jupyter supports languages Julia, R, Haskell & Ruby, in addition to Python. IPython continues to be a Python shell and a kernel for Jupyter.

To install IPython, you can use pip, Python's package manager. In the command prompt/Terminal, enter

$ pip install ipython

This should install IPython on your computer. If it doesn't, I suggest you look at this post for problem resolution.

If pip is not working, it might be due to the fact that it is not in your path environment variable. One workaround for this issue is to run pip as a script by using the -m flag of python command line.

$ python -m pip install ipython

To launch an IPython notebook, go to command prompt/Terminal, navigate to the directory where you would like to store your notebook, and then execute the following command to launch the Jupyter Notebook App in a browser tab:

$ jupyter notebook 

For more options, refer to Jupyter Running the Notebook.

For usage examples, the IPython team has created this iPython notebook. Check it out.

In the command prompt where you executed the startup command, press Ctrl + C to exit the notebook.

Here's a handy link to Shortcuts and helpful tips for working in IPython and Jupyter. And another one.


Calculating maximum & minimum valued element of an iterable: min() & max()

The builtin max() and min() functions are used to find out the maximum & minimum valued elements of the given iterable.

>>> max( [1, 2, 3, 4] )
4
>>> min( [1, 2, 3, 4] )
1


>>> max( ['a', 'b', 'c'] )
'c'
>>> min( ['a', 'b', 'c'] )


>>> max( ['apple', 'attic', 'aardvark'] )
'attic'
>>> min( ['apple', 'attic', 'aardvark'] )
'aardvark'

These functions have another implementation, one in which they take more than iterable as inputs and compare the iterables themselves. The max() compares corresponding elements of the iterables, and at the first point of differentiation, returns the larger of the iterable. The min() does the inverse.

>>> max ( [1, 2], [1, 3], [1, 4] )
[1, 4]

>>> min ( [1, 2], [1, 3], [1, 4] )
[1, 2]

That's the jist of it. But there are a couple of optional keyword arguments these functions accept. To know more about them, and about how Python compares values, visit this link.


Calculating the sum of elements of an iterable: sum()

The builtin sum() function returns the summation of an iterable of numbers. It has an optional second positional argument, which denotes the value to start the summation with. Its default value is 0. In the event that the iterable is empty, it returns the value of 'start'.

>>> sum( [1, 2, 3, 4] )
10
>>> sum( range(1, 11) )
55

Sorting an iterable: sorted()

Python's builtin sorted() function sorts the elements an iterable object in ascending order and returns a list of the ordered elements.

>>> anUnsortedList = [3, 6, 1, 2]
>>> sorted(anUnsortedList)
[1, 2, 3, 6]

>>> anUnsortedString = 'bca'
>>> sorted(anUnsortedString)
['a', 'b', 'c']

This is a rudimentary application of the sorted() function. It has two optional keyword arguments: reverse and key. To know more about them, read this piece on the sorted() function.


Most Commonly Used Third-Party Modules

Python has a huge collection of third-party modules, owing to its large community. In this list, I provide to you the most commonly used external modules. Each of these modules is available on The Cheese Shop, can be installed using pip and imported using the import statement after installation. In front of the name of each module, there are two links. One links to its either its home page or its documentation having usage examples, the other is the module's page on The Cheese Shop.


Most Commonly Used Standard Library Modules

Python comes with over 200 standard library modules. In this list, I provide to you the most commonly used ones in Python 3. Each of these modules can be imported using the import statement. Each module links to official Python documentation citing examples to work with it. To view the helptext along with objects contained in the modules, execute help(module_name).


Chain of Assignments

You can assign a value to many variables in a single statement.

>>> a = 10
>>> c = b = a
>>> a
10
>>> b
10
>>> c
10

Operator Precedence in Python

Following is the order in which operators in Python are evaluated. The operators at the top are evaluated first, and ones lower down the order are evaluated later.

Operator(s) Name of Operator(s)
() Parentheses
** Exponentiation
+a, -a, ~a Positive, negative, bitwise NOT
*, /, //, % Multiplication, division, floor division, modulus
+, - Addition, subtraction
<<, >> Shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, == Membership, identity & comparisons
not a Boolean NOT
and Boolean AND
or Boolean OR

Note that there are cases when 2 or more operators have the same precedence e.g. *, /. If a Python expression has multiple operators of the same precedence, the order of evaluation in such cases is left to right. The one occurring on the left is evaluated first. For example:

>>> 2 * 8 / 4			# (2 * 8) / 4
4.0
>>> 2 / 8 * 4			# (2 / 8) * 4
1.0

The exception to left-to-right order is the exponent operator, which has right-to-left associativity.

>>> 2 ** 2 ** 2			# 2 ** (2 ** 2)
16

Zen of Python: import this

Although not really a tip or a trick, it's worth knowing that the this module reveals a list of guidelines which the Python developers had in mind while developing the language. It encapsulates the philosophy that an ideal Python developer should follow.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

See also: 50+ Know-How(s) Every Pythonista Must Know


Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply