16 Python Tricks To Learn Before You Write Your Next Code

Tricks that will make your life easier as a python developer

Muhammad Abdullah Arif
6 min readApr 4, 2023

Python is a versatile programming language that can be used for a wide range of applications, from web development to data analysis. However, as with any programming language, there are certain tricks and techniques that can help you write more efficient, elegant, and maintainable code. In this article, we’ll share 16 Python tricks that you should learn before you write your next code.

1 . List Comprehension

List comprehension is a concise way to create a list in Python. It is faster and more efficient than using loops and conditionals to create a list.
The Syntax
newlist = [expression for item in iterable if condition == True]
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name. Without list comprehension you will have to write a for statement with a conditional test inside:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

With list comprehension you can do all that with only one line of code:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

2. Lambda Function

Lambda function is a small, anonymous function that can be defined in a single line. It is useful when you need to define a function that will be used only once.
The Syntax
lambda arguments : expression
Example:

x = lambda a : a + 10
print(x(5))

3. Using enumerate()

Using enumerate() is a Pythonic way to loop over a sequence and keep track of the index of the current item.
The Syntax
enumerate(iterable, start=0)
Example:

# Python program to illustrate
# enumerate function
l1 = ["eat", "sleep", "repeat"]
s1 = "Python"

# creating enumerate objects
obj1 = enumerate(l1)
obj2 = enumerate(s1)

print ("Return type:", type(obj1))
print (list(enumerate(l1)))

# changing start index to 2 from 0
print (list(enumerate(s1, 2)))

"""
Output
Return type:
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'P'), (3, 'y'), (4, 't'), (5, 'h'),, (6, 'o'), , (7, 'n')]
"""

4. Using zip()

Using zip() is a Pythonic way to loop over two or more sequences at the same time.
The Syntax
zip(iterator1, iterator2, iterator3 ...)
Example:

a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica", "Vicky")

x = zip(a, b)

"""
Output
(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
"""

5. Using map()

Using map() is a Pythonic way to apply a function to each item in a sequence and return a new sequence.
The Syntax
map(function, iterables)
Example:

def myfunc(n):
return len(n)

x = map(myfunc, ('apple', 'banana', 'cherry'))

6. Using filter()

Using filter() is a Pythonic way to select elements from a sequence that satisfy a certain condition.
The Syntax
filter(function, iterable)
Example:

ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
if x < 18:
return False
else:
return True

adults = filter(myFunc, ages)

for x in adults:
print(x)

7. Using setdefault()

Using setdefault() is a Pythonic way to set a default value for a dictionary key if the key does not exist.
The Syntax
dictionary.setdefault(keyname, value)
Example:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.setdefault("model", "Bronco")

print(x)

"""
Output

Mustang
"""

8. Using defaultdict()

Using defaultdict() is a Pythonic way to create a dictionary with default values for all keys.
The Syntax
defaultdict(default_factory)
Parameters
default_factory:
A function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.
Example:

# Python program to demonstrate
# defaultdict


from collections import defaultdict


# Function to return a default
# values for keys that is not
# present
def def_value():
return "Not Present"

# Defining the dict
d = defaultdict(def_value)
d["a"] = 1
d["b"] = 2

print(d["a"])
print(d["b"])
print(d["c"])

9. Using Counter()

Using Counter() is a Pythonic way to count the number of occurrences of each item in a sequence.
Example:

# import counter class from collections module
from collections import Counter

# Creation of a Counter Class object using
# string as an iterable data container
x = Counter("PythonForEveryone")

# printing the elements of counter object
for i in x.elements():
print ( i, end = " ")

10. Using any() and all()

Using any() and all() are Pythonic ways to check if any or all elements in a sequence satisfy a certain condition.
The Syntax
all(list of iterables)
any(list of iterables)

Example:

# Since all are false, false is returned
print (any([False, False, False, False]))

# Here the method will short-circuit at the
# second item (True) and will return True.
print (any([False, True, False, False]))

# Here the method will short-circuit at the
# first (True) and will return True.
print (any([True, False, False, False]))


# Here all the iterables are True so all
# will return True and the same will be printed
print (all([True, True, True, True]))

# Here the method will short-circuit at the
# first item (False) and will return False.
print (all([False, True, True, False]))

# This statement will return False, as no
# True is found in the iterables
print (all([False, False, False]))

11. Using context managers

Using context managers is a Pythonic way to manage resources like files, sockets, and locks.
Example:

# Python program creating a
# context manager

class ContextManager():
def __init__(self):
print('init method called')

def __enter__(self):
print('enter method called')
return self

def __exit__(self, exc_type, exc_value, exc_traceback):
print('exit method called')

with ContextManager() as manager:
print('with statement block')

""" Output
init method called
enter method called
with statement block
exit method called
"""

12. Using decorators

Using decorators is a Pythonic way to modify the behavior of a function or a class.
Syntax for Decorator:

@gfg_decorator
def hello_decorator():
print("Gfg")
'''Above code is equivalent to -def hello_decorator():
print("Gfg")

hello_decorator = gfg_decorator(hello_decorator)'''
Example:

13. Using generators

Using generators is a Pythonic way to generate a sequence of values without creating a list.
The Syntax
(expression for item in iterable)
Example:

def my_generator(n):

# initialize counter
value = 0

# loop until counter is less than n
while value < n:

# produce the current value of the counter
yield value

# increment the counter
value += 1

# iterate over the generator object produced by my_generator
for value in my_generator(3):

# print each value produced by generator
print(value)

14. Using itertools

Using itertools is a Pythonic way to work with iterators and generate combinatorial sequences.
Example:

from itertools import count

for number in count(start=1, step=2):
if number > 10:
break
print(number) # print statement

15. Using *args and **kwargs

Using *args and **kwargs is a Pythonic way to define functions with variable-length arguments.
The Syntax
“We use the “wildcard” or “*” notation like this — *args OR **kwargs — as our function’s argument when we have doubts about the number of arguments we should pass in a function.”

Example:

def myFun(*args, **kwargs):
print("args: ", args)
print("kwargs: ", kwargs)


# Now we can use both *args ,**kwargs
# to pass arguments to this function :
myFun('python', 'for', 'everyone', first="Python", mid="for", last="Everyone")

"""Output
args: ('python', 'for', 'everyone')
kwargs: {'first': 'Python', 'mid': 'for', 'last': 'Everyone'}
"""

16. Using f-strings

Using f-strings is a Pythonic way to format strings that is faster and more concise than other string formatting methods.
Example:

# Python3 program introducing f-string
val = 'Python'
print(f"{val} is a programming language for {val} lovers.")


name = 'Abdullah'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Learning these Python tricks will help you write better, more efficient, and more elegant code. So, whether you are a beginner or an experienced Python developer, take some time to master these tricks and take your Python programming skills to the next level!

If you enjoyed this article, be sure to follow me on Medium for more tricks and tips! Follow the link to my profile to stay updated on the latest insights and ideas.

Link: Muhammad Abdullah Arif — Medium

Good luck!

--

--

Muhammad Abdullah Arif

Python developer. The facts are the facts but opinions are my own.