MyPage is a personalized page based on your interests.The page is customized to help you to find content that matters you the most.

I'm not curious

10 simple yet useful tips on Python Programming

Published on 15 May 15
10 simple yet useful tips on Python Programming - Image 1

As many of you may know, Python is a commonly used high-level programming language. The core benefit of python is to boost code readability, whereby the program’s language arrangement allows coders to write concepts in fewer lines of codes as compared to other programming languages such as Java. Python’s language has constructs that delivers clear and concise programs for both small and big developer projects. Python supports various programming forms, including object orientation, imperative styles and functional programming styles.

Now moving on from the basic concepts, here are 10 simply useful and, well you might say essential, tips for the average programmer like you.
1) Writing functions with its variable lists
One of the awesome things about Python is with its variable parameter lists. Programmers can simply write functions without even knowing what sort of parameters will be passed.
Let’s focus on the codes listed below the asterisk at the first marks parameter may be any positional parameters.

def lessThan(cutoffMark, *marks) :

''' Return a list of values less than the cutoff. '''

arr = []

for val in marks :

if val < cutoffMark:


return arr

After using the function, we get:



>>> print(lessThan(10, 2, 17, -3, 42))

[2, -3]

Looking at the first positional value we state in the function call (10) that is given to the first parameter in the function (cutoffMark), it will cause all the remaining positional values to be assigned to marks. Scanning through these values, we can then search for those that are smaller than the cutoff value.

2) Apply the same technique used in tip 1 with named parameters
Likewise with named parameters, as shown below, a double asterisk place at the dict parameter below means any named parameters. Python will then be able to provide us with value pairs in dictionary form.
def printVals(prefix='', **dict):
# Print out the extra named parameters and their values
for key, val in dict.items():
print('%s [%s] => [%s]' % (prefix, str(key), str(val)))

After using the function, we get:
>>> printVals(prefix='..', foo=42, bar='!!!')
[foo] => [42]
[bar] => [!!!]
>>> printVals(prefix='..', one=1, two=2)
[two] => [2]
[one] => [1]
As extra named parameters are passed through in a dictionary, which is an un-ordered data structure, the values are not printed out in the same order as they were not defined in the function call.
3) Using True and False as Indexes
A technique you can use to select values is to use True and False as list indexes. The technique is useful due to the fact that False == 0 and True == 1:
# 's
1test = True
2# test = False
3result = ['Test is False','Test is True'][test]
4# result is now 'Test is True'
This method is simple and you wouldn’t encounter any hiccups when the value_if_true must actually be true.
However, do bear in mind that this method only works when you know the test is False or True (0 or 1), but not other integer values or arbitrary objects.
4) Improving Python performance with multiple approaches
If you intend on placing similar coding approaches whenever you create an application, it could cause your application to run slower than before. For instance, when handling codes in a dictionary, you may adopt a secured approach of dictating whether an item exists and update it or you can choose an alternative option by adding the item directly and then handling the given circumstances where the item does not exist as an exception.

Focusing on the safe and secured approach first,
p = 16
myDiction = {}
for i in range(0, p):
char = 'abcd'[i%4]
if char not in myDict:
myDiction[char] = 0
myDiction[char] += 1
As predicted, the code will normally perform quicker when myDict is empty at the beginning. However, when myDict is filled or almost filled with data, the alternative option is proven to be better as based on the set of codes listed below.
p = 16
myDiction = {}
for I in range(0, p):
char = ‘abcd’[i%4]
myDiction[char] += 1
except KeyError:
myDiction[char] = 1
Based on the 2 coding examples listed above, the output of {'d': 4, 'c': 4, 'b': 4, 'a': 4} is similar. However, the only difference is the manner in which output is obtained. That being said, it’s certainly helpful for programmers to take the unconventional approach to boost your python’s performance speed.
5) Remember to optimize your loops
One of the beautiful things when working with Python is that you can depend on plenty of different techniques for making loops run faster. However, one crucial reminder while optimizing loops is that you have to prevent yourself from using dots within a loop. For instance, let’s focus on the series of codes listed below:
lowerlist = ['this', 'is', 'lowercase']
upper = str.upper
upperlist = []
append = upperlist.append
for word in lowerlist:
#Output = ['THIS', 'IS', 'LOWERCASE']
Whenever you need to make a call to str.upper, Python assess the technique. On the other hand, if you place such an evaluation in a variable, the value will be known and Python can perform the tasks quicker than before. The fact of the matter is that you should lessen the amount of work that Python performs within loops as the Python software can probably slow things down based on that example.
Of course, there are other ways to optimize loops such as using list comprehensions, which could be argued to be the next best alternative in achieving faster loops.
6) Useful tip to check whether a file exist in Python
With python, there are several ways you can use to see whether a file does exist (and is accessible) from a directory. One way is by using the os.path.isfile path. This function will be true if the given path is an prevailing, ordinary file. The file adopts symbolic links, which makes foros.path.islink(path) to be true and os.path.isfile(path) to also be true. The os.path.isfile is a very practical one liner function that helps to check if a file exists.
7) Mixing Python and shell scripts
It could be useful for you to write a script that can function as a shell script or as a Python script at the exact time, which is probable. To do it, the sequence of four quote characters requires an empty string to the shell, but in Python it begins as a triple-quoted string that has a quote character. So you can embed shell commands within the python triple-quoted string. Take note that the first string in a module or script can be simply stored as the doc string for that module, but besides that the Python interpreter will just ignore it.
The below example display this particular trick.

if which python >/dev/null; then
exec python "$0" "$@"
echo "${0##*/}: Python not found. Please install Python." >&2
exit 1

__doc__ = """
Demonstrate how to mix Python + shell script.

import sys
print "Hello World!"
print "This is Python", sys.version
print "This is my argument vector:", sys.argv
print "This is my doc string:", __doc__
sys.exit (0)
8) Know how to translate signal numbers to names
As of now, there is no existing function in the "signal" module that allows programmers to be able to change a signal number to a signal name. However, the listed example below could be a handy function for you to use.
def signal_numtoname (num):
name = []
for key in signal.__dict__.keys():
if key.startswith("SIG") and getattr(signal, key) == num:
name.append (key)
if len(name) == 1:
return name[0]
return str(num)
9) Using a member of set type
You may not know, but there have been concepts that can boil down to operations on a set. Need to ensure that your list does not have duplicates? Or looking to see whether your two lists have anything common? Python does have a set function that allows you to make these operations quick and easy to read.
Also, you can use the intersection function to compare all the items. After which, you will be able to return them once the items have both sets in common.
# deduplicate a list *fast*
print(set(["chicken", "eggs", "bacon", " chicken "]))
# {'bacon', 'eggs', chicken }

# compare lists to find differences/similarities
# {} without "key":"value" pairs makes a set
menu = {"pancakes", " chicken ", "eggs", "bacon"}
new_menu = {"coffee", " chicken ", "eggs", "bacon", "bagels"}

new_items = new_menu.difference(menu)
print("Try our new", ", ".join(new_items))
# Try our new bagels, coffee

discontinued_items = menu.difference(new_menu)
print("Sorry, we no longer have", ", ".join(discontinued_items))
# Sorry, we no longer have pancakes

old_items = new_menu.intersection(menu)
print("Or get the same old", ", ".join(old_items))
# Or get the same old eggs, bacon, chicken

full_menu = new_menu.union(menu)
print("At one time or another, we've served:", ", ".join(full_menu))
# At one time or another, we've served: coffee, chicken, pancakes, bagels, bacon, eggs
10) Setting up Virtualenv in python
As virtualenv is a very important function for sand-boxing Python environments, as it allows you to form independent Python contexts that are similar to separate sandboxes. Which is definitely a better than modifying the global python environment.
One of the key benefits of sandboxing your Python environment is that you can easily test your code under different Python versions and package dependencies.
To install virtualenv, you need to set up pip first. As such follow these commands:
# easy_install is the default package manager in CPython
% easy_install pip
# Install virtualenv using pip
% pip install virtualenv
% virtualenv python-workspace # create a virtual environment under the folder 'python-workspace'
With the new virtualenv set up under 'python-workspace', you have to activate the Python environment in order for the current shell to move into the virtualenv:

% cd python-workspace

% source ./bin/activate # activate the virtualenv 'python-workspace'

% python # enter an interpreter shell by executing the current virtual python program under 'python-workspace/bin/python'
We have come to the end of my top ten tips for Python programmers. Do leave a comment below if you have other tips to share! Happy coding everyone!
This blog is listed under Open Source and Development & Implementations Community

Related Posts:



Web Development

Post a Comment

Please notify me the replies via email.

  • We hope the conversations that take place on will be constructive and thought-provoking.
  • To ensure the quality of the discussion, our moderators may review/edit the comments for clarity and relevance.
  • Comments that are promotional, mean-spirited, or off-topic may be deleted per the moderators' judgment.
You may also be interested in
Awards & Accolades for MyTechLogy
Winner of
Top 100 Asia
Finalist at SiTF Awards 2014 under the category Best Social & Community Product
Finalist at HR Vendor of the Year 2015 Awards under the category Best Learning Management System
Finalist at HR Vendor of the Year 2015 Awards under the category Best Talent Management Software
Hidden Image Url