How To Simplify Python For Loops
Why Do Python For Loops Need Simplification?
There's a classic problem every programmer has when they start using Python or other languages with a similar feature: for loops can iterate directly over most iterables or be indexed.
This does not sound like a problem, since more choices should not lead to worse results. The problem is not that the results are any worse, it's that there is a simple way to get the both of best worlds that many programmers just do not use: enumerate().
How It Works
The first thing I want to highlight about working with Python, is that you can define multiple variables in a single line using commas. This is important to enumerate() since we want the best of both worlds.
def ret2():
return 2,22
a,b = ret2()
print(a,b)
(2,22)
Next, let's look at what enumerate() is actually doing. So first, I will make a list, l, and call enumerate() on it.
l = ['a','b','c','d']
e = enumerate(l)
If we printed e now, it would look something like:
<enumerate object at 0x7fb7c0566780>
But, if we iterate through the object we get:
for i in e:
print(i)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
So, enumerate() returns tuples with the positional data first and the position's item second. Imagine we want to combine two 3X3 matrices element by element. Except in certain cases, we'll do something different just to show off enumerate().
Example
l = [[4,3,1],[6,7,3],[9,3,5]]
l2 = [[0,2,2],[0,9,4],[5,5,1]]
l_out = []
for i in range(len(l)):
l_temp = []
for j in range(len(i)):
if l[i][j] == 6 and l2[i][j] == 0:
l_temp += [l[i][j]]
elif l[i][j] == 3:
l_temp += [l2[i][j]]
else:
l_temp += combine(l[i][j], l2[i][j])
l_out += [l_temp]
l = [[4,3,1],[6,7,3],[9,3,5]]
l2 = [[0,2,2],[0,9,4],[5,5,1]]
l_out = []
for i,row in enumerate(l):
l_temp = []
for j,val in enumerate(i):
if val == 6 and l2[i][j] == 0:
l_temp += [val]
elif val == 3:
l_temp += [l2[i][j]]
else:
l_temp += combine(val, l2[i][j])
l_out += [l_temp]
Conclusion
Using enumerate(), you can cut out many indexing calls to a list. There are much better uses of enumerate(), but you'll have to find them through practice. enumerate()'s usefulness can vary from making a for loop more readable, to simplifying a problem to fewer lines of code.
Nicely explained. However, you can add more about loop of python. Cheers.