Introduction

I have been using Python, and I noticed some interesting Pythonic way to avoid wring for loop and if-else statements

For Loop

List Comprehension/Generator

result = []
for item in item_list:
    new_item = do_something(item)
    result.append(new_item)

This is a typical example of transforming a list of items into another, and there is a very Pythonic implementation for that

result = [do_something(item) for item in item_list]

Function

If you want to use a function to transform the list, you can use map function

result = map(do_something, item_list)

For example

squared = map(lambda x: x**2, range(10))

Extract Functions or Generators

The above two methods are very useful when you want to extract a function or generator from a list

How about more complicated examples?

results = []
for item in item_list:
    # setup

    # condition

    # processing

    # calculation
    results.append(result)

Obviously you are overloading a code block.

Instead, you can do:

results = []
def process(item)
    # setup

    # condition

    # processing

    # calculation
    return result

results = [process(item) for item in item_list]

How about nested for loop?

results = []
for item in item_list:
    for sub_item in sub_item_list:
        # setup

        # condition

        # processing

        # calculation
        results.append(result)

To switch it to a list comprehension, you can do:

results = [process(item, sub_item)
           for item in item_list
           for sub_item in sub_item_list]

If you want to record some inner state of the list

a = [2,8,5,6,4,3,9,7,1]
results = []
current = 0

for i in a:
    current = max(current, i)
    results.append(current)

print(results)

# [2, 8, 8, 8, 8, 8, 9, 9, 9]

We can use generator to do the same thing

def max_generator(a):
    current = 0
    for i in a:
        current = max(current, i)
        yield current

a = [2,8,5,6,4,3,9,7,1]
results = list(max_generator(a))
print(results)

# [2, 8, 8, 8, 8, 8, 9, 9, 9]

Wait a minute, is there a for loop in the generator?

We could do it with itertools.accumulate

import itertools
a = [2,8,5,6,4,3,9,7,1]
results = list(itertools.accumulate(a, max))
print(results)

# [2, 8, 8, 8, 8, 8, 9, 9, 9]

If-Else

Ternary Operator

if condition:
    x = true_value
else:
    x = false_value

can be written as

x = true_value if condition else false_value

Probability Space

if condition:
    x = true_value
else:
    x = false_value

can also be written as

x = [false_value, true_value][condition]

Conclusion

Most of the time, you don’t need to write for loop and if-else statements, and you can use list comprehension, map, generator, ternary operator, and probability space to do the same thing.

I hope you find this post useful. If you have any questions, please contact me via email or GitHub