Coding

6 Python Tricks You Should Know

Python is among the highest in-demand and popular programming languages in 2021. According to the TIOBE Index, Python occupies the second position. Netflix, IBM, and hundreds of other companies utilize Python. And, these companies usually have a dedicated software development team, to accomplish every task that involves Python. You can also hire a developer for this. Even Dropbox is created using this powerful and popular programming language.

Compared to other programming languages, Python offers the following benefits –

  • Multiple open-source tools and frameworks
  • Compatible with major operating systems (OS) and platforms
  • Robust standard library
  • Maintainable and readable code
  • Standard test-driven development

Like every other programming language, it has its own set of tricks and tips that you’re probably unaware of. Below you’ll find some of the lesser-known tricks of Python that will teach you how to use Python on Mac, desktop, and other platforms.

1. Utilizing list comprehensions

List comprehensions are utilized for the creation of new lists from other iterables. Since list comprehensions return lists, they typically consist of brackets that contain the expression. The expression is executed for each element along with the for loop so that it can be iterated over each element.

As list comprehensions are optimized for the Python interpreter to easily spot a predictable pattern during looping, it is faster.

For instance, here’s how you can find the squares of the first 5 whole numbers by using list comprehensions.

m = [x ** 2 for x in range(5)]

print(m) # [0, 1, 4, 9, 16]

Now, here’s how you can find the common numbers from the 2 list by utilizing list comprehensions.

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]

2. Concatenating strings

If you have to concatenate a list of strings, it can be done by using a for loop and you can add each element one by one. However, this method is going to be quite inefficient, especially if your list is very long. In Python, the strings are immutable, and therefore, the right and left strings would have to be copied into a new string or each pair of concatenation.

Using the join () function would be a better approach. An example is shown below.

characters = [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

word = “”.join(characters)

print(word) # python

3. Making use of ZIP when working with lists

Say, for instance, you were given the task of combining several lists with the same length and also print out the result. Here, take a look at a more generic way to achieve the desired result by using zip () as shown 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

4. Iterate with enumerate ()

The enumerate () method helps to add a counter to an iterable. It also returns it in a form of enumerating object. Here is an example of how the popular coding interview question, known as the FizzBuzz problem can be solved.

When you have to write a program that helps you print the numbers in a list for multiples of 3, you can print “fizz” in place of the number and for the multiples of 5, you can print “buzz”. Print “fizzbuzz” for multiples of 3 and 5.

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’]

5. Making use of the Python collections

Python collections refer to container data types which are sets, lists, dictionaries, and tuples. The module of the collections offers high-performance data types that can improve your code and make things much easier and cleaner. The collections module provides a lot of functions. To demonstrate this, you will have to use the Counter () function.

The Counter () function uses an iterable like a tuple or list and returns it to the Counter Dictionary. The unique elements present in the iterable will be the dictionary’s keys. The value of each key will be the count of the elements that are present in the iterable.

To create a counter object, an iterable (list) has to be passed to counter () function. Take a look at the example.

from collections import Countercount = Counter([‘a’,’b’,’c’,’d’,’b’,’c’,’d’,’b’])

print(count) # Counter({‘b’: 3, ‘c’: 2, ‘d’: 2, ‘a’: 1})

6. Return of multiple values from a function

From a function call, Python can return multiple values. This is something that is missing from other programming languages. In this case, the return values ought to be a comma-separated list of values. Then, Python will construct a tuple and return it to the caller. Find an example below.

def multiplication_division(num1, num2):

return num1*num2, num1/num2

product, division = multiplication_division(15, 3)

print(“Product=”, product, “Quotient =”, division) # Product= 45 Quotient = 5.0

So, here are the Python tricks and tips that will help to sharpen your code skills.

 

 

Francis L. Crosby

Recent Posts

The Essential Role of Animated Explainer Videos in Tech Documentation

In an era dominated by the relentless advancement of technology, how we consume information has…

2 months ago

Maximize Brand Reach: Top PR Strategies for All Platforms

In the ever-evolving digital landscape, distinguishing your brand amidst a sea of competitors requires a…

2 months ago

Optimizing Your Compensation: The Role of a Personal Injury Attorney After an Accident

Situated in the picturesque Willamette Valley, Salem offers a supportive legal environment where individuals can…

2 months ago

How to Get Started With CTV Advertising in Albuquerque, NM?

In the evolving landscape of digital marketing, Connected TV (CTV) advertising emerges as a powerful…

3 months ago

The Essential Elements of a Successful UX Audit Template

User Experience (UX) ensures a website or application's success in the fast-paced digital design world.…

3 months ago

How Playing Video Games Has Changed the Current Generation

When American physicist William Higinbotham created the world’s first video game way back in 1958,…

3 months ago