Simple tricks to optimize your Python code

Ashwin Goel
4 min read12 hours ago

Disclaimer: All these tips and tricks are strictly for python. Many other programming languages might not provide such functionalities which are discussed below.

Swap

How do you swap the values of two variables x & y?

temp = x
x = y
y = temp

Really? Now try this:

x, y = y, x

Isn’t that cool?

map() function

The map() function is one of the most useful functions in python.

It basically takes all the elements from an iterator(list, string, tuple etc..), sends it to the function and returns a data type map which is also an iterator.

Syntax: map(function, iterator)

# This function returns square of a number n
def square(n):
return n*n
l = [1, 2, 3, 4, 5]
l2 = map(square, l)
# map is another data type and a map object cannot be simply printed
print(list(l2))
# l2 = [1, 4, 9, 16, 25]

map() is generally used in competitive programming for taking inputs:

# Suppose input in "1 2 3 4 5 6"
l = list(map(int, input().split()))
# input.split() creates an array of string numbers: ["1", "2", ...]
# int is a function which converts the number from string to integer data type.
# Finally, l = [1, 2, 3, 4, 5, 6]

--

--

Ashwin Goel
Ashwin Goel

Written by Ashwin Goel

Software Engineer @ JPMorgan Chase & Co.

No responses yet