Top 10 Python tips

Built-in Method: sum, max, min

sum method will return the sum of iterable data type (List is one of iterable data type in Python)

print(sum([2, 7, 1]))

max method will return the highest value of iterable data type

print(max([2, 7, 1]))

min method will return the lowest value of iterable data type

print(min([2, 7, 1]))

Printing path of the imported module

If we need to print the file directory or path for the Python modules we have imported in the programs, then we just have to use the module name inside the print statement simply, and the file directory will be printed in the output. Example: Looking at the following Python program: Output:

Obtain Current Date and Time

Python has a built-in module datetime that is versatile in working with dates and times. One of its methods, .now(), returns the current date and time:

Printing the most occurred element of a list

We have given a list with a number of elements in it, and there are many elements in it that are repeated more than one time. Now, if we want to print the number of elements that are occurred most in the list and it is the same as finding mode in statistics from the given data of numbers. We use max() and count function to get the result of the most occurred element. Example: Output:

Use xrange() instead of range().

Python 2 used the functions range() and xrange() to iterate over loops. The first of these functions stored all the numbers in the range in memory and got linearly large as the range did. The second, xrange(), returned the generator object. When looping with this object, the numbers are in memory only on demand.

import sys
numbers = range(1, 1000000)

This returns 8000064, whereas the same range of numbers with xrange returns 40. If your application is in Python 2, then swapping these functions can have a big impact on memory usage. The good news is that Python 3 implements the xrange() functionality by default. So, while there’s no xrange() function, the range() function already acts like this.

Learn itertools.

It’s been called a gem. If you haven’t heard of it, then you’re missing out on a great part of the Python standard library. You can use the functions in itertools to create code that’s fast, memory efficient, and elegant. Dive into the documentation, and look for tutorials to get the most out of this library. One example is the permutations function. Let’s say you wanted to generate all the permutations of [“Alice”, “Bob”, “Carol”].

import itertools
iter = itertools.permutations(["Alice", "Bob", "Carol"])

This function will return all possible permutations:

[('Alice', 'Bob', 'Carol'),
 ('Alice', 'Carol', 'Bob'),
 ('Bob', 'Alice', 'Carol'),
 ('Bob', 'Carol', 'Alice'),
 ('Carol', 'Alice', 'Bob'),
 ('Carol', 'Bob', 'Alice')]

It’s really useful and blazingly fast!

Using itertools

The Python itertools module is a collection of tools for handling iterators. itertools has multiple tools for generating iterable sequences of input data. Here I will be using itertools.combinations() as an example. itertools.combinations() is used for building combinations. These are also the possible groupings of the input values. Let’s take a real world example to make the above point clear.

Suppose there are four teams playing in a tournament. In the league stages every team plays against every other team. Your task is to generate all the possible teams that would compete against each other.

Let’s take a look at the code below: The important thing to notice is that order of the values doesn’t matter. Because ('Team 1', 'Team 2') and ('Team 2', 'Team 1') represent the same pair, only one of them would be included in the output list. Similarly we can use itertools.permutations() as well as other functions from the module. For a more complete reference, check out this amazing tutorial.

Merging Python and Shell Scripts

Now, this is something you can’t do with C or C++. If you are an open-source guy, you would surely use Linux as the main Operating OS, or at least a Dual Boot. So, Linux already includes python. And python is extremely compatible with Linux. This gives us the benefit of compiling and merging them together. You can simply create a script that can work as a normal Unix script as well as an interpreted Python code at the same time. When writing a shell script, you need a four quote character and an empty string to the shell, but you need to do that with a triple-quoted string with a quote character in python. Remember that the first string in a script can be easily stored as a doc string for a module, but after that, the python interpreter will simply ignore it. An example is as follows: #!/bin/sh 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)

Format Strings with f-Strings (Python 3.6+)

This is new since Python 3.6 and in my opinion is the best way to format a string. We just have to write an f before our string, and then inside the string we can use curly braces and access variables. This is much simpler and more concise compared to the old formatting rules, and it's also faster. Moreover, we can write expressions in the braces that are evaluated at runtime. So here for example we want to print the squared number of our variable i, and we can simply write this operation in our f-String.

name = "Alex"
my_string = f"Hello {name}"
print(my_string) # Hello Alex

i = 10
print(f"{i} squared is {i*i}") # 10 squared is 100

Concatenating Strings

When you need to concatenate a list of strings, you can do this using a for loop and adding each element one by one. However, this would be very inefficient, especially if the list is long. In Python, strings are immutable, and thus the left and right strings would have to be copied into the new string for every pair of concatenation. A better approach is to use the join() function as shown below:

# Naive way to concatenate strings
sep = ['a', 'b', 'c', 'd', 'e']
joined = ""
for x in sep:
    joined += x


# Joining strings
sep = ['a', 'b', 'c', 'd', 'e']
joined = "".join(sep)