According to Stack Overflow, Python is the fastest growing programming language. The latest report from Forbes states that Python showed a 456-percent growth in last year. Netflix uses Python, IBM uses Python, and hundreds of other companies all use Python. Let’s not forget Dropbox. Dropbox is also created in Python. According to research by Dice Python is also one of the hottest skills to have and also the most popular programming language in the world based on the Popularity of Programming Language Index.
Some of the advantages Python offers when compared to other programming languages are:
- Compatible with major platforms and operating systems
- Many open-source frameworks and tools
- Readable and maintainable code
- Robust standard library
- Standard test-driven development
Python Tips and Tricks
In this piece, I’ll present 10 useful code tips and tricks that can help you in your day-to-day tasks. So without further ado, let’s get started.
1. Concatenating Strings
When you need to concatenate a list of strings, you can do this using a for loop by 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:characters = ['p', 'y', 't', 'h', 'o', 'n']
word = "".join(characters)
print(word) # python
2. Using List Comprehensions
List comprehensions are used for creating new lists from other iterables. As list comprehensions returns lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. List comprehension is faster because it is optimized for the Python interpreter to spot a predictable pattern during looping.
As an example let’s find the squares of the first five whole numbers using list comprehensions.
m = [x ** 2 for x in range(5)]
print(m) # [0, 1, 4, 9, 16]
Now let’s find the common numbers from two list using list comprehension
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = [a for a in list_a for b in list_b if a == b]
print(common_num) # [2, 3, 4]
3. Iterate With enumerate()
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object.
Let’s solve the classic coding interview question named popularly as the Fizz Buzz problem.
Write a program that prints the numbers in a list, for multiples of ‘3’ print “fizz” instead of the number, for the multiples of ‘5’ print “buzz” and for multiples of both 3 and 5 it prints “fizzbuzz”.
numbers = [30, 42, 28, 50, 15]
for i, num in enumerate(numbers):
if num % 3 == 0 and num % 5 == 0:
numbers[i] = 'fizzbuzz'
elif num % 3 == 0:
numbers[i] = 'fizz'
elif num % 5 == 0:
numbers[i] = 'buzz'
print(numbers) # ['fizzbuzz', 'fizz', 28, 'buzz', 'fizzbuzz']
4. Using ZIP When Working with Lists
Suppose you were given a task to combine several lists with the same length and print out the result? Again, here is a more generic way to get the desired result by utilizing
zip()as shown in the code below:countries = ['France', 'Germany', 'Canada']
capitals = ['Paris', 'Berlin', 'Ottawa']
for country, capital in zip(countries,capitals):
print(country, capital) # France Paris
Germany Berlin
Canada Ottawa
5. 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:
import itertools
friends = ['Team 1', 'Team 2', 'Team 3', 'Team 4']
list(itertools.combinations(friends, r=2)) # [('Team 1', 'Team 2'), ('Team 1', 'Team 3'), ('Team 1', 'Team 4'), ('Team 2', 'Team 3'), ('Team 2', 'Team 4'), ('Team 3', 'Team 4')]
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.6. Using Python Collections
Python collections are container data types, namely lists, sets, tuples, dictionary. The collections module provides high-performance datatypes that can enhance your code, making things much cleaner and easier. There are a lot of functions provided by the collections module. For this demonstration, I will be using
Counter() function.
The
Counter() function takes an iterable, such as a list or tuple, and returns a Counter Dictionary. The dictionary’s keys will be the unique elements present in the iterable, and the values for each key will be the count of the elements present in the iterable.
To create a
counter object, pass an iterable (list) to Counter() function as shown in the code below.from collections import Countercount = Counter(['a','b','c','d','b','c','d','b'])
print(count) # Counter({'b': 3, 'c': 2, 'd': 2, 'a': 1})
For a more complete reference, check out my python collections tutorial.


0 Comments