search
HomeBackend DevelopmentPython TutorialDetailed explanation of examples of for loops in python

This article mainly introduces some thoughts about the use of for loop in Python. Friends who need it can refer to

Why should we challenge ourselves not to write for in the code? loop? Because this forces you to use more advanced and authentic 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.

This is a challenge. I want you to avoid writing for loops under any circumstances. Similarly, I also want you to find a scenario where it is too difficult to write in any other way except using a for loop. Please share your findings, I'd love to hear about them

It's been a while since I started exploring awesome Python language features. In the beginning, it was just a challenge I gave myself to practice using more language features instead of what I had learned from other programming languages. But things gradually get more interesting! Not only does the code become shorter and cleaner, it also looks more structured and regular, and I'll talk more about these benefits in this article.

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

1. Traverse a sequence to extract some information

2. From the current Generate another sequence from the sequence

3. Writing for loops is 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 mind and see things from a different perspective.

What will you gain by not writing for loops everywhere

1. Fewer lines of code

2. Better code readability

3. Only use indentation to manage code text

Let's see the code skeleton below:

Look at the structure of the following code:


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

This example uses multiple levels of nested code, which is very difficult to read. 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"

To avoid for loops, you can use these tools

1. List analysis/GeneratorExpression

Look at a simple example. This example mainly compiles a new sequence based on an existing sequence:


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

If you like MapReduce, you can use map, or Python's list parsing:

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

Similarly, if you just want to get an iterator, you can use a generator expression with almost the same syntax. (How could you not fall in love with Python's consistency?)

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

2. Function

Think about it in a higher-order, more functional way. If you want to map one sequence to another, call the map function directly. (List comprehension can also be used instead.)

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

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


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

In addition, a large number of built-in functions in Python can/will (I don’t know if this is a good thing or a bad thing, you choose one, it is a bit not to add this sentence Difficult to understand) Consume iterator:


>>> 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 expressions

The above two methods handle relatively simple logic well , what about more complex logic? As programmers, we abstract difficult things into functions, and this approach can be used here as well. If you write this kind of code:


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

Obviously you are giving too much responsibility to a piece of code. 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]

How about nested for loops?


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

List comprehensions can help you:


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

What if you want to save 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
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]

Let’s extract an expression to implement these:


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))

“Wait, you just did that A for loop is used in the expression of the function, which is cheating! "

Okay, smart guy, try this.

4. Don’t write the for loop yourself, itertools will do it for you

This module is really wonderful. I believe this module can cover 80% of the times when you want to write a for loop. For example, the previous example can be rewritten like this:


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

In addition, if you are iterating over a sequence of combinations, there are product(), permutations(), and combinations() that can be used .

Conclusion

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

2. You should avoid using for loops, which will make the code more readable.

Action

1. Look at your code again and find any place where you have written a for loop intuitively before. Think about it again and write it without a for loop. Again it doesn't make sense.

2. Share an example where it was difficult for you not to use a for loop.

The above is the detailed content of Detailed explanation of examples of for loops in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.