Moment For Technology

Reduce the use of loops in Python

Posted on Dec. 2, 2022, 6:25 p.m. by Mannat Mane
Category: The back-end Tag: python The back-end Gold Mining Translation Project
  • Minimize for loop usage in Python
  • By Rahul Agarwal
  • Translation from: The Gold Project
  • This article is permalink:
  • Translator: qiuyuezhong
  • Proofreader: MollyAredtana and Shixi-Li

Reduce the use of loops in Python

How and why should you reduce the use of loops in Python?

Python gives us a variety of encoding options.

In a way, this is quite inclusive.

People from any language can write Python.

However, learning to write a language and writing a language in an optimal way are two different things.

In this series of articles called Python Shorts, I'll explore some of the simple but very useful structures that Python provides, along with some tips and examples that I've encountered in my data science work.

In this article, I'll discuss for loops in Python and how to avoid them as much as possible.

There are three ways to write a for loop:

Let me illustrate with a simple example.

Suppose you want to get the sum of squares of a list.

In machine learning, we all face this problem when we want to calculate the distance between two points in n dimensions.

You can do this easily using loops.

In fact, I'd like to show you three ways I've seen to accomplish the same task, and let you choose which one you think is best.

x = []
sum_squared = 0

for i in range(len(x)):
Copy the code

When I see the above code in Python code, I know this person has a C or Java background.

A more Pythonic way to accomplish the same thing is:

x = []
sum_squared = 0

for y in x:
Copy the code

That's even better.

I didn't index this list. And my code is more readable.

However, the more Pythonic way can be done in one line.

x = []
sum_squared = sum([y**2 for y in x])
Copy the code

This method is called List Comprehension, and it's probably one of the reasons I fell in love with Python.

You can also use if in List Comprehension.

Suppose we only want the list of even squares.

x = []
even_squared = [y**2 for y in x if y%2= =0]
# Output results:
Copy the code


What if we want an even number squared and an odd number cubed?

x = []
squared_cubed = [y**2 if y%2= =0 else y**3 for y in x]
# Output results:
Copy the code

That's great!

So, in general, follow this specific rule: Whenever you want to write a for statement, you should ask yourself the following questions,

  • Don't have toforDo it? More Pythonic style.
  • Can I do that using List Comprehension? If so, use it.
  • Can I not index arrays? If not, consider using itenumerate.

What is enumerate?

Sometimes we need both the index in the array and the value in the array.

In this case, I prefer to use Enumerate instead of indexed lists.

L = ['blue'.'yellow'.'orange']
for i, val in enumerate(L):
    print("index is %d and value is %s" % (i, val))
# Output results:
index is 0 and value is blue
index is 1 and value is yellow
index is 2 and value is orange
Copy the code

Here's a rule:

Never index a list if you can't use it.

Try using Dictionary Comprehension

You can also try Dictionary Comprehension, which is a relatively new addition to Python and has a syntax similar to List Comprehension.

Let me illustrate with an example. I want to get a dictionary (key: square) for each value in x.

x = []
{k:k**2 for k in x}
# Output results:
{1: 1.2: 4.3: 9.4: 16.5: 25.6: 36.7: 49.8: 64.9: 81}
Copy the code

What if you just want a dictionary with even values?

x = []
{k:k**2 for k in x if x%2= =0}
# Output results:
{2: 4.4: 16.6: 36.8: 64}
Copy the code

What if I want to get an even number squared and an odd number cubed?

x = []
{k:k**2 if k%2= =0 else k**3 for k in x}
# Output results:
{1: 1.2: 4.3: 27.4: 16.5: 125.6: 36.7: 343.8: 64.9: 729}
Copy the code


Finally, I will say that while it may seem easy to transfer knowledge from other languages to Python, if you continue to do so, you will miss the beauty of Python. When we use it the way Python does, it's much more powerful and much more interesting.

So, when neededforWhen looping, use List Comprehensions and Dictionary Comprehensions. Use when an array index is neededenumerate.

Avoid a cycle like an epidemic

In the long run, your code will be more readable and maintainable.

Also, if you want to learn more about Python 3, I would recommend Intermediate Level Python, an excellent course at the University of Michigan. Definitely check it out.

In the future I will also write more articles suitable for beginners. Please let me know what you think of this series. Follow me on Medium or subscribe to my blog for more information.

As always, I welcome feedback and constructive comments, which can be reached on Twitter at @mlWhiz.

Originally published on April 23,

If you find any errors in the translation or other areas that need improvement, you are welcome to revise and PR the translation in the Gold Translation program, and you can also get corresponding bonus points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.

Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.