The latest technology and digital news on the web

Powered by

6 applied tricks every Python developer should have

  • Tech
  • Python (programming language)

6 applied tricks every Python developer should have

Python has become a accepted programming accent because it is clear, versatile, easy to learn, and it has plenty of useful libraries for altered tasks. From web development to data science and cybersecurity, Python programmers are high in demand. 

But like all programming languages, in Python, aggregate depends on you, the programmer. You decide whether your code looks able or ugly.

Fortunately, Python has a vast array of congenital appearance that can help you write code that is elegant, concise, and expandable, the kind of characteristics you expect from a able programmer.

Here some of my admired tricks, which I think every Python developer should know.

1. List comprehensions

List comprehensions are one of the key appearance of Python that help you write code that is more abridged and elegant. Let’s say you want to create an array absolute numbers from 1 to 100. The acceptable way to do it would be to use the range() function:

numbers = list(range(1, 101))

But what if you wanted to do commodity more complicated, such as creating a list of squares from 1 to 100? In that case, the archetypal way would be to use a for loop:

numbers = []

for i in range(1, 101):


This is the accepted way that most programming languages support. But fortunately, in Python, list comprehensions make things a lot easier. Here’s what the same code would look like when accounting in list apperception mode:

numbers = [i**2 for i in range(1, 101)]

You can use list comprehensions to pack several instructions and expressions in the brackets that define a list. They’re much beneath and more affected than the for loop. And there’s a lot more you can do while still befitting your code clean. For instance, say you have a action is_prime() that checks an input number and allotment True if it’s a prime number. The afterward code atom creates a list of squares of primes from 1 to 100 by adding is_prime() a action to the comprehension.

2. Zipping

Another Python affection that comes handy every once in a while is the zip() function. zip combines two or more lists into a single variable. Say you have calm a list of chump names, their ages, and their admired ice cream flavor.

customers = ['John', 'Natasha', 'Eric', 'Sally']

ages = [26, 31, 39, 22]

flavors = ['cherry', 'chocolate', 'strawberry', 'lemon'] 

Using zip(), you can consolidate all three lists into a single list where each entry contains a tuple with the name, age, and adopted flavor of one customer.

combined = zip(customers, ages, flavors)

customers_ice_cream = list(combined)

This is what your customers_ice_cream list looks like after zipping the data:

[('John', 26, 'cherry'),

 ('Natasha', 31, 'chocolate'),

 ('Eric', 39, 'strawberry'),

 ('Sally', 22, 'lemon')]

And here’s how the zipped list can be used in a loop:

for cust in customers_ice_cream:

        print("{} is {} years old and likes {}".format(*cust))

The output looks like this:

John is 26 years old and likes cherry

Natasha is 31 years old and likes chocolate

Eric is 39 years old and likes strawberry

Sally is 22 years old and likes lemon

3. Counting items

Often, you want to know how many times a assertive value occurs in a list. For instance, say we’ve calm a list of 1-10 ratings from an online survey. To simulate this, we’ll accomplish a list of 1,000 random numbers from 1 to 10 using the randint() function.

from random import randint

ratings = [randint(1, 10) for _ in range(1,1001)]

Now, we want to know how many of each rating is included in the list. One way to do this is to use the congenital count action of the list. count() takes a value and allotment the number of times that value occurs in the list.

for i in range(1, 11):

    print("{}: {} occurences".format(i, ratings.count(i)))

This code produces the afterward output:

1: 95 occurrences

2: 115 occurrences

3: 111 occurrences

4: 109 occurrences

5: 81 occurrences

6: 110 occurrences

7: 80 occurrences

8: 94 occurrences

9: 98 occurrences

10: 107 occurrences

However, this only works if you know in beforehand what is the range of values in your list. In case you don’t know the accessible values, you can use a set, which creates a list of unique items independent in addition list. For instance, if you have a list of names and want to know how many times each name has occurred you can use the afterward code.

for name in set(names):

    print("{}: {} occurences".format(name, names.count(name)))

Alternatively, you can use the Counter class, which specializes in counting values in lists.

from collections import Counter

ratings_count = Counter(ratings)

for rating in ratings_count:

    print("{}: {} occurences".format(rating, ratings_count[rating]))

Counter provides some added functionality, such as the most_common() function, which gives you the most occurring values in a list. For instance, the afterward code will print out the three most-popular values:

for rating in ratings_count.most_common(3):

    print("{}: {} occurences".format(*rating))

4. Enumerating

Sometimes, you want to keep track of the count of items as you iterate through a list. Say you have a list of chump names and you want to list them along with their index number. Here’s one way to do it:

for i in range(len(customers)):

    print("{}: {}".format(i 1, customers[i]))

This would aftermath an output that looks commodity like this:

1: Samantha

2: Mara

3: Eric

4: James

5: George

6: Toni

7: Margaret

8: Steven

While this code works, it’s not very elegant. Notice the conflict amid the index and the counter? Fortunately, Python has an enumerate() action that makes your index-tracking code much more barefaced and adorable to the eye. enumerate() takes two arguments, the list you want to enumerate and the starting number of the counter, and gives two outputs at each round of the loop, the adverse value and the list item. Here’s what the same botheration is solved with enumerate.

for i, chump in enumerate(customers, 1):

    print("{}: {}".format(i, customer)) 

Much better.

5. Constant expansion

Say you have a action that processes apprentice information:

def process_student_info(first_name, last_name, fav_topic, score):

    print(first_name, last_name, fav_topic, score)

In many cases, the values you want to pass to the action are included in a list or dictionary object that has been busy from a database or text file. In such cases, calling the action would be a bit clunky:

process_student_info(student[0], student[1], student[2], student[3])

Fortunately, Python “parameter expansion” feature, which enables you to anon pass an entire list to a function. By adding a * at the alpha of the list’s name, you expand it to its alone values before appointment it to the function.


Parameter amplification with lists works as long as the number of ambit and their arrangement is agnate to the ambit of the target function. In case of a mismatch, it will raise an error.

You can also use constant amplification with dictionaries, in which case, the order of values doesn’t matter. You only need to have keys that accord to your action parameters. Constant amplification for dictionaries requires the ** abettor before the object.

student = {'last_name': 'doe', 'score': 89, 'first_name': 'john', 'fav_topic': 'calculus'}


One of the allowances of using concordance amplification is that if your action has absence parameters, abbreviating them in your concordance won’t raise an error.

6. Type annotations

Python is a dynamically-typed language, which means if you try to mix variables that have altered data types, it usually finds a way to boldness the aberration or raises an barring if it can’t. But this adaptability can also result in capricious behavior.

Say you have a action that multiplies two variables.

def mul(a, b):

    return a * b

if you call mul() on two integers or floats — your advised use for the action — the result is predictable.

a = 5

b = 6

print(mul(a, b))

But what if one of your variables is a list?

a = [1, 2, 4, 5]

b = 3

print(mul(a, b))

The action creates a list that is three concatenated copies of the list. This is acutely not what you wanted to do. Python versions 3.6 and higher accommodate “type annotations,” a affection that enables you to define the type of data each action altercation should take. Here’s how the type annotated mul() function looks like.

def mul(a: int, b: int): 

    return a * b

This format absolutely states that mul() takes two accumulation values. To be clear, type comment won’t anticipate you from using the action in adventitious ways. But there are some good affidavit to use it anyway.

First, defining the type of data is a form of documentation, and makes it easier for other developers going through your code to accept what type of data you expect in your action (compare the annotated and non-annotated versions of the function).

But even more importantly, some code editors action type annotations and help you with appearance such as autocomplete and type errors.

Screenshot of Spyder IDE assuming autocomplete for typed variable.

Closing thoughts

These were six of my admired Python tricks. Using them will make your code abridged and elegant. With Python fast acceptable the defacto programming accent in many domains and institutions, having a good set of best practices will ensure you can be a advantageous member of your development team.

This commodity is brought to you by Rijksoverheid. 

Published September 23, 2020 — 13:18 UTC

Hottest related news

No articles found on this category.
No articles found on this category.