Challenging Yourself to Avoid Using For Loops

(Click the blue text above to quickly follow us)

Compiled by: Bole Online – Xin Zai

If you have good articles to submit, please click → here for details

Why challenge yourself to avoid writing for loops in your code? Because it forces you to use more advanced and idiomatic syntax or libraries. This article uses Python as an example to discuss many syntaxes that you may have seen in others’ code but rarely use yourself.

This is a challenge. I want you to avoid writing for loops under any circumstances. Similarly, I want you to find a scenario where it is too difficult to write using methods other than for loops. Please share your findings; I am very eager to hear them.

It has been a while since I started exploring the amazing features of the Python language. Initially, it was just a challenge I set for myself to practice using more language features instead of relying on what I learned from other programming languages. However, things gradually became more interesting! The code not only became shorter and cleaner but also appeared more structured and organized. In this article, I will elaborate on these benefits.

First, let’s take a step back and look at the intuition behind writing a for loop:

  1. Iterating over a sequence to extract some information

  2. Generating another sequence from the current sequence

  3. Writing for loops has become second nature to me because I am a programmer

Fortunately, Python already has great tools to help you achieve these goals! All you need to do is change your mindset and look at the problem from a different angle.

What will you gain by not writing for loops everywhere?

  1. Fewer lines of code

  2. Better code readability

  3. Using indentation only for managing code structure

Let’s see the code skeleton below:

Here’s the structure of the code:

# 1

with:

for:

if:

try:

except:

else:

This example uses deeply nested code, which is very difficult to read. I found that this code indiscriminately uses indentation to mix management logic (with, try-except) and business logic (for, if). If you adhere to the convention of using indentation only for management logic, then the core business logic should immediately stand out.

“Flat structures are better than nested structures” – The Zen of Python

To avoid for loops, you can use these tools:

1. List Comprehensions/Generator Expressions

Here’s a simple example that compiles a new sequence based on an existing sequence:

result = []

foritem initem_list:

new_item = do_something_with(item)

result.append(item)

If you like MapReduce, you can use map, or Python’s list comprehension:

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

Similarly, if you just want to get an iterator, you can use the almost identical syntax of generator expressions. (How can you not love Python’s consistency?)

result = (do_something_with(item) for item in item_list)

2. Functions

Consider a higher-order, more functional programming approach. If you want to map one sequence to another, directly call the map function. (List comprehension can also be used as a substitute.)

doubled_list = map(lambda x: x * 2, old_list)

If you want to reduce a sequence to a single element, use reduce:

fromfunctools import reduce

summation = reduce(lambdax,y: x + y,numbers)

Additionally, Python has many built-in functions that can (I don’t know if this is a good thing or a bad thing, you choose one; omitting this sentence makes it a bit hard to understand) consume iterators:

>>> a = list(range(10))

>>> a

[0,1,2,3,4,5,6,7,8,9]

>>> all(a)

False

>>> any(a)

True

>>> max(a)

9

>>> min(a)

0

>>> list(filter(bool,a))

[1,2,3,4,5,6,7,8,9]

>>> set(a)

{0,1,2,3,4,5,6,7,8,9}

>>> dict(zip(a,a))

{0: 0,1: 1,2: 2,3: 3,4: 4,5: 5,6: 6,7: 7,8: 8,9: 9}

>>> sorted(a,reverse=True)

[9,8,7,6,5,4,3,2,1,0]

>>> str(a)

‘[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]’

>>> sum(a)

45

3. Extracting Functions or Expressions

The above two methods handle simpler logic well, but what about more complex logic? As programmers, we abstract difficult tasks into functions, and this approach can also be applied here. If you wrote this code:

results = []

foritem initem_list:

# setups

# condition

# processing

# calculation

results.append(result)

Clearly, you have given a piece of code too much responsibility. To improve, I suggest you do this:

def process_item(item):

# setups

# condition

# processing

# calculation

return result

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

What about nested for loops?

results = []

fori inrange(10):

forj inrange(i):

results.append((i,j))

List comprehensions can help you:

results = [(i,j)

fori inrange(10)]

forj inrange(i)]

What if you need to maintain a lot of internal state?

# finding the max prior to the current item

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

results = []

current_max = 0

fori ina:

current_max = max(i,current_max)

results.append(current_max)

# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

Let’s extract an expression to achieve this:

def max_generator(numbers):

current_max = 0

fori innumbers:

current_max = max(i,current_max)

yield current_max

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

results = list(max_generator(a))

“Wait, you just used a for loop in that function expression, that’s cheating!”

Well, clever person, try this one instead.

4. Don’t write for loops yourself; let itertools do it for you

This module is amazing. I believe it can cover 80% of the times you want to write a for loop. For example, the previous example can be rewritten as:

from itertools import accumulate

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

results = list(accumulate(a,max))

Additionally, if you are iterating over combinations of sequences, you can use product(), permutations(), and combinations().

Conclusion

  1. In most cases, there is no need to write for loops.

  2. For loops should be avoided as they lead to better code readability.

Action

  1. Review your code again, identify any places where you previously wrote for loops by intuition, and reconsider whether it makes sense to rewrite them without for loops.

  2. Share examples where you found it difficult to avoid using for loops.

Did you gain something from this article? Please share it with more people.

Follow “Python Developers” to enhance your Python skills

Challenging Yourself to Avoid Using For Loops

Leave a Comment