Minimize for loop usage in Python

if not, think about using enumerateWhat is enumerate?Sometimes we need both the index in an array as well as the value in an array.

In such cases, I prefer to use enumerate rather than indexing the list.

L = ['blue', 'yellow', 'orange']for i, val in enumerate(L): print("index is %d and value is %s" % (i, val))—————————————————————index is 0 and value is blueindex is 1 and value is yellowindex is 2 and value is orangeThe rule is:Never index a list, if you can do without it.

Try Using Dictionary ComprehensionAlso try using dictionary comprehension, which is a relatively new addition in Python.

The syntax is pretty similar to List comprehension.

Let me explain using an example.

I want to get a dictionary with (key: squared value) for every value in x.

x = [1,2,3,4,5,6,7,8,9]{k:k**2 for k in x}———————————————————{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}What if I want a dict only for even values?x = [1,2,3,4,5,6,7,8,9]{k:k**2 for k in x if x%2==0}———————————————————{2: 4, 4: 16, 6: 36, 8: 64}What if we want squared value for even key and cubed number for the odd key?x = [1,2,3,4,5,6,7,8,9]{k:k**2 if k%2==0 else k**3 for k in x}———————————————————{1: 1, 2: 4, 3: 27, 4: 16, 5: 125, 6: 36, 7: 343, 8: 64, 9: 729}ConclusionTo conclude, I will say that while it might seem easy to transfer the knowledge you acquired from other languages to Python, you won’t be able to appreciate the beauty of Python if you keep doing that.

Python is much more powerful when we use its ways and decidedly much more fun.

So, use List Comprehensions and Dict comprehensions when you need afor loop.

Use enumerate if you need array index.

Avoid for loops like plagueYour code will be much more readable and maintainable in the long run.

Also if you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan.

Do check it out.

I am going to be writing more beginner friendly posts in the future too.

Let me know what you think about the series.

Follow me up at Medium or Subscribe to my blog to be informed about them.

As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.

Originally published at https://mlwhiz.

com on April 23, 2019.


. More details

Leave a Reply