10 Python Tips and Tricks You Should Learn Today
Check out this collection of 10 Python snippets that can be taken as a reference for your daily work.
By Abhinav Sagar, VIT Vellore
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:
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.
Now let’s find the common numbers from two list using list comprehension
3. Iterate With
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”.
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:
5. Using itertools
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.
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 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.
For a more complete reference, check out my python collections tutorial.
7. Convert Two Lists Into a Dictionary
Let’s say we have two lists, one list contains names of the students and second contains marks scored by them. Let’s see how we can convert those two lists into a single dictionary. Using the zip function, this can be done using the code below:
8. Using Python Generators
Generator functions allow you to declare a function that behaves like an iterator. They allow programmers to make an iterator in a fast, easy, and clean way. Let’s take an example to explain this concept.
Suppose you’ve been given to find the sum of the first 100000000 perfect squares, starting with 1.
Looks easy right? This can easily be done using list comprehension but the problem is the large inputs size. As an example let’s take a look at the below code:
On increasing the perfect numbers we need to sum over, we realize that this method is not feasible due to higher computation time. Here’s where Python Generators come to the rescue. On replacing the brackets with parentheses we change the list comprehension into a generator expression. Now let’s calculate the time taken:
As we can see, time taken has been reduced quite a bit. This effect will be even more pronounced for larger inputs.
For a more complete reference, check out my article Reduce Memory Usage and Make Your Python Code Faster Using Generators.
9. Return Multiple Values From a Function
Python has the ability to return multiple values from a function call, something missing from many other popular programming languages. In this case the return values should be a comma-separated list of values and Python then constructs a tuple and returns this to the caller. As an example see the code below:
10. Using sorted() Function
Sorting any sequence is very easy in Python using the built-in method
sorted()which does all the hard work for you.
sorted()sorts any sequence (list, tuple) and always returns a list with the elements in sorted manner. Let’s take an example to sort a list of numbers in ascending order.
Taking another example, let’s sort a list of strings in descending order.
In this article, I’ve presented 10 Python tips and tricks that can be used as a reference in your day-to-day work. I hope you enjoyed this article. Stay tuned for my next piece, “Tips and Tricks to Speed Up Your Python Code”.
Curated collection of useful Python snippets that you can understand in 30 seconds or less. Contributions welcome…
50+ Python 3 Tips & Tricks
These Python Gems Will Make Your Code Beautiful and Elegant
A Guide to Python Itertools
Those iterables are more powerful than you can possibly imagine.
If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details:
Happy reading, happy learning, and happy coding!
Bio: Abhinav Sagar is a senior year undergrad at VIT Vellore. He is interested in data science, machine learning and their applications to real-world problems.
Original. Reposted with permission.
- Python Lists and List Manipulation
- Python Dictionary and Dictionary Methods
- Why Python is One of the Most Preferred Languages for Data Science?