Part 2. Compact code and Comprehensions#

2.1 Compact Code#

Compact code is often more efficient and easier to read. Python provides several ways to create compact code, including comprehensions and lambda functions.

Compact code is the way to write code in a more concise and efficient manner. It often involves using built-in functions, comprehensions, and other techniques to reduce the number of lines of code while maintaining readability.

2.1.1 One-Line If and Else#

We can write simple if-else statements in one line. If we have two variables a and b, we can assign the larger of the two to a new variable max_value like this:

a = 10
b = 20

if a < b:
    print('a is greater than b')
else:
    print('a is not greater than b')

# Using one-line if-else
print('a is greater than b' if a<b else 'a is not greater than b')

We can even do this with more complicated conditional structures:

if a < b:
    c='less than'
elif a>b:
    c='greater than'
else:
    c='equal to'
    
print('a is', c, 'b')

# Using one-line if-elif-else

print('a is', 'less than' if a<b else 'greater than' if a>b else 'equal to', 'b')

2.1.2 One-Line For Loops#

We can also write simple for loops in one line. For example, if we want to print each element in a list, we can do it like this:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# Using one-line for loop
[print(fruit) for fruit in fruits]

2.2 Comprehensions#

Comprehensions provide a concise way to create iterable objects, such as lists, dictionaries, sets, or generators. Example:

# Traditional way to create a list
l=[]
for i in range(11):
    l.append(i)  
print(l)

# Using list comprehension
l = [i for i in range(11)]
print(l)

Comprehensions consist of brackets containing an expression followed by a for clause, and can also include if clauses for filtering.

2.2.1 List, Set and Dictionary Comprehensions#

# List comprehension with a condition
l = [i for i in range(11) if i%2==0]
print(l)

# Or even simpler
l = [i*2 for i in range(6)]
print(l)

We can also add conditions to comprehensions:

# List comprehension with a condition
l = [i for i in range(11) if i%2==0]
print(l)

# Another example
words = ['zero','one','two','three','four','five','six','seven','eight','nine','ten']
l = [i if i%4==0 else words[i] for i in range(11) if i%2==0]
print(l)

# Example using set comprehension
s = {i%3 for i in range(30)}
print(s)

# Example using dictionary comprehension
d = {i:words[i] for i in range(11) if i%2==0}
print(d)

# Another example using dictionary comprehension
nums = [i for i in range(11)]
d = {word:num for word,num in zip(words,nums)}
print('d =',d)
d_even = {word:num for word,num in d.items() if num%2==0}
print('d_even =',d_even)

2.2.2 Generator Expressions#

Generator expressions are similar to list comprehensions, but they use parentheses instead of square brackets. They generate items one at a time and are more memory efficient for large datasets.

# Generator expression
gen = (i*2 for i in range(6))
print(gen)  # This will print the generator object
for value in gen:
    print(value)  # This will print each value generated

Instead of an iterable containing all of it’s elements generators distinguish themselves by storing the information to generate elements. For instance, the function range() is a generator. We can make our own generators with a similar sintax to what is used in comprehensions except now with ().

gen = (i*2 for i in range(6))
print(gen)  # This will print the generator object
for value in gen:
    print(value)  # This will print each value generated