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.
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:
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.
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:
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”.
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
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:
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. For a more complete reference, check out my python collections tutorial.
Lambda functions are also called anonymous functions as they don’t have names. They are used a lot in fields like Data Science, ML, Backend using Django, and many more. Let’s check an example to add two numbers. Simple Function:
def add(a,b):
return a + b
add(1,8)
Lambda function:
add = lambda a,b : a+b
add(1,8)
Lambda functions are often useful to allow quick calculations or processing as the input to other functions. They make code easier to read if they're used appropriately.
This method will give users a good experience in simple menu-based applications as well. The getpass module will be used to read in passwords from the users in the console applications. Example:
from getpass import getpass
username = input("username: ")
password = getpass("password : ")
Output:
username: Ayesha145
password: *******
This method hides the user input for the password field on the console. You can use this method while making any management system project (the professors just love to assign such projects☹) to make the user experience better. Cool trick, isn't it?