Replace for loops and make Python code more pythonic!

Text | Parson Sauce

Source: Python Technology

c8a12e46473e5552f1336e858089a42d.jpeg

Why challenge yourself not to write a for loop in your code? Because this forces you to learn to use more advanced and more idiomatic syntax or libraries. The article uses python as an example to talk about a lot of syntax that everyone has seen in other people’s code but rarely uses it themselves.

It’s been a while since I started exploring the amazing language features in Python. In the beginning, I gave myself a challenge with the goal of allowing me to practice more Python language features than I would have had programming experience with other programming languages. This makes things more and more interesting! The code becomes more and more concise, and the code looks more structured and standardized. I will describe these benefits below.

Usually the for loop is used in the following usage scenarios:

  • to extract some information in a sequence.

  • Generate one sequence from another.

  • Writing for has become a habit.

Fortunately, Python already has a lot of tools to help you do this, you just need to shift your mind and think about it from a different perspective.

What you gain by avoiding writing for loops:

  • Less code

  • Better code readability

  • Less indentation (still makes sense for Python)

Let’s take a look at the following code structure:

# 1
with ...:
    for ...:
        if ...:
            try:
            except:
        else:

In this example, we are dealing with multiple levels of nested code, which is difficult to read. This example uses multiple levels of nested code. What I found in this code was the indiscriminate use of indentation to mix management logic (with, try-except) and business logic (for, if). If you adhere to the convention of only using indentation for administrative logic, then the core business logic should be taken out immediately.

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

Existing tools you can use to replace for loops

1.List Comprehension / Generator expression

Let’s look at a simple example. If you want to convert an array to another array:

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

If you like MapReduce, you can also use map, or List Comprehension in Python:

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

Likewise, if you just want to iterate over the elements in an array, you can use the same code Generator Expression. result = (do_something_with(item) for item in item_list)

2. Function

If you want to map one array into another array, you can solve this problem in a more advanced and practical programming way by simply calling the map function.

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

If you want to reduce a sequence to a single one, use reduce

from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)

Additionally, many Python built-in functions use iterables:

>>> 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.Extract Functions or Generators

The above two methods are good for handling simpler logic. How about more complex logic? As programmers, we write functions to abstract away complex business. The same idea applies here. If you write like this:

results = []
for item in item_list:
    # setups
    # condition
    #processing
    # calculation
    results.append(result)

Clearly you’re adding too much responsibility to a block of code. Instead, I suggest you do:

def process_item(item):
    # setups
    # condition
    #processing
    # calculation
    return result


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

What would happen if we changed to a nested function?

results = []
for i in range(10):
    for j in range(i):
        results.append((i, j))

Replace it with List Comprehension to achieve this:

results = [(i, j)
           for i in range(10)
           for j in range(i)]

If your code block needs to log some 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
for i in a:
    current_max = max(i, current_max)
    results.append(current_max)


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

We use a generator to achieve this:

def max_generator(numbers):
    current_max = 0
    for i in numbers:
        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))

Readers may ask, “Wait a minute! You used a for loop in the generator, that’s cheating! Don’t worry, look at the code below.

Don’t write it yourself, itertools does it for you.

This module is very simple and I believe this module can replace your original for loop in most scenarios.

For example, the last example could be rewritten as:

from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))

In addition, if you want to iterate over a combination sequence, you need to use product(), permutations(), combinations().

Conclusion

In most cases, you don’t need to write a for loop.

You should avoid writing for loops for better code readability.

The big era is coming. It doesn’t matter if you don’t understand AI, but you must understand AI, use AI, and be exposed to it. Don’t miss this crazy news, Welcome to subscribe to our brochure : (Chatgpt cheats are here >), 43 useful articles, and more than 700 subscribing partners are already on board. It’s just the price of 2 cups of coffee. Read forever.

Recommended reading:
Getting Started: The most comprehensive problem of learning Python from scratch | Learned Python for 8 months from scratch | Practical projects | This is the shortcut to learn Python

Essential information: Crawling Douban short reviews, the movie “The Next Us” | Analysis of the best NBA players in 38 years | From highly anticipated to word of mouth! Detective Tang 3 is disappointing | Watch the new Legend of Heaven and Dragon Sword with laughter | The king of lantern riddle answers | Use Python to make a massive sketch of young ladies | Mission: Impossible is so popular, I use machine learning to make a mini recommendation system for movies

Fun: Pinball game | Nine-square grid | Beautiful flowers | Two hundred lines of Python “Tiantian Cool Run” game!

AI: A robot that can write poetry | Colorize pictures | Predict income | Mission: Impossible is so popular, I use machine learning to make a mini movie recommendation system

Gadget: Convert Pdf to Word, easily convert tables and watermarks! | Save html web pages to pdf with one click! | Goodbye PDF extraction charges! | Use 90 lines of code to create the most powerful PDF converter, one-click conversion of word, PPT, excel, markdown, and html | Create a DingTalk low-price ticket reminder! |60 lines of code made a voice wallpaper switcher that I can watch every day! |

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeBasic grammarLoop 389176 people are learning the system