Python: Less is more

·

3 min read

Hello, code lovers! In this article, we will explore features of Python that enable us to write less code. We will mention each feature and see with a practical example, how it can be used to reduce the quantity of code. Readability will not be the focus of this article, although you will find that most of the examples do maintain readability as well.

List comprehensions

Example: Create a list of all multiples of 3 less than 10.

Using list comprehension:

example_list = [i for i in range(1, 10) if i % 3 == 0]

Without list comprehension:

example_list = []
for i in range(1, 10):
    if i % 3 == 0:
        example_list.append(i)

Ternary statements

Example: Find which number is greater.

Using ternary statement:

a = 3
b = 4
max = a if a > b else b

Without ternary statement:

a = 3
b = 4
if(a > b):
    max = a
else:
    max = b

F-strings

Example: Concatenate an integer variable to a string.

Using f-string:

a = 5
print(f"The value of a is {a}") # Output: The value of a is 5

Without using f-string:

a = 5
print("The value of a is " + str(a)) # Output: The value of a is 5

lambda/anonymous functions

Example: Write a function to calculate the sum of two numbers.

Using lambda:

sum = lambda a, b: a+b
print(sum(2,4)) # Output: 6

Without using lambda:

def sum(a,b):
    return a + b
print(sum(2,4)) # Output: 6

map

Example: Square each number in a list.

Using map:

example_list = [1, 2, 3, 4]
squares_of_list = list(map(lambda x: x*x, example_list))

Without using map:

example_list = [1, 2, 3, 4]

squares_of_list = []
for item in example_list:
    squares_of_list.append(item * item)

filter

Example: Find all the negative numbers in a list.

Using filter:

example_list = [-3, -2, -1, 0, 1, 2, 3]
result = list(filter(lambda item: item < 0, example_list))

Without filter:

example_list = [-3, -2, -1, 0, 1, 2, 3]
result = []
for i in example_list:
    if i < 0:
        result.append(i)

reduce

Example: Find the sum of the numbers in a list.

Using reduce:

from functools import reduce

numbers = [1, 2, 3, 4]
sum = reduce(lambda a, b: a + b, numbers)

Without reduce:


numbers = [1, 2, 3, 4]
sum = 0
for n in numbers:
    sum += n

Generator expressions

Example: Write a generator that returns the cube of numbers between 0 and 10.

Using generator expressions:

cube_generator = (i ** 3 for i in range(0,10))

Without using generator expressions:

def cube_generator():
   for i in range(0,10):
        yield i ** 3

zip

Example: Iterate over two lists and print the values.

Using zip:

a = [1, 3, 5, 9]
b = ['a', 'b', 'c']

for item in zip(a,b): # stops when the shortest list is exhausted
    print(item[0], item[1])

Without using zip:

a = [1, 3, 5, 9]
b = ['a', 'b', 'c']

i = 0
while i<len(a) and i<len(b):
    print(a[i], b[i])
    i += 1

Tuple swap

Example: Swap two variables

Using tuple swap:

a = 1
b = 2

a,b = b,a

Without using tuple swap:

a = 1
b = 2

temp = a
a = b
b = temp

Negative Indexing

Example: Get the last item in a list

With negative indexing:

example_list = [1, 2, 3, 4]

print(example_list[-1])  # Output: 4

Without negative indexing:

example_list = [1, 2, 3, 4]

print(example_list[len(example_list)-1]) # Output: 4

Thanks for reading the article and I hope it was helpful.