Sunday, June 30, 2019

The for in Loop In Python

One of the strongest features, in my opinion, that Python has is its ability to work with sequences. Sequences are ranges, lists, tuples, sets and dictionaries. I think that pythons elegance in working with these sequences is due to the design decision not to include extra syntax.

Most languages have two for statements...the for loop and the for in loop. Python only uses the for in loop and has a built in function called range (xrange in python 2.7) to do basic indexing.

for i in range(10): print(i)
Because python uses zero indexes the above example prints 0-9 and not 1-10. Ranges actually stop at count-1.

It's tempting to use the above form of the for loop to iterate or cycle through all indexes of a list as the below example shows but there are better ways to accomplish the same task.

lst = [0,1,2,3,4,5,6,7,8,9]
for i in range(len(10)): 
  print(i)
This is not the most pythonic or cleanest way to loop through a list.


Counting indexes and passing the length to the range function is just a little too much work and is really unnecessary because you can accomplish the same thing by passing the list directly into the for in loop.

for value in [0,1,2,3,4,5,6,7,8,9]: 
  print(value)
I just passed a literal list into the above code but I could have passed in a list variable like I do in the below examples.

For most cases the above syntax is all that is needed and I estimate that I use it 90% of the time and rarely use any other looping mechanism. I suspect that the gate keepers of Python had the same experience and that is why they chose only two loop structures ( while and for in ). Programmers coming from a different language such as C++, C# or Java are usually quick to resort to the range function because they need access to the index not just the value. However, python has a better solution to this problem by using the built-in function enumerate.

The below example uses the enumerate function to iterate through all values in a list with the for in loop and print the index and the value accordingly.


>>> lst = [10, 3, -1, 40, 9, 1, 0, 3, 3]
>>> for index, value in enumerate(lst):
...   print("index: " + str(index) + " value: " + str(value))
... 
index: 0 value: 10
index: 1 value: 3
index: 2 value: -1
index: 3 value: 40
index: 4 value: 9
index: 5 value: 1
index: 6 value: 0
index: 7 value: 3
index: 8 value: 3
>>> 
This implementation would be blessed by the python elders and priests.

The same task using the range function, as shown below, is a little more wordy and is more difficult to debug.


>>> lst = [10, 3, -1, 40, 9, 1, 0, 3, 3]
>>> for index in range(len(lst)):
...   print("index: " + str(index) + " value: " + str(lst[index]))
... 
index: 0 value: 10
index: 1 value: 3
index: 2 value: -1
index: 3 value: 40
index: 4 value: 9
index: 5 value: 1
index: 6 value: 0
index: 7 value: 3
index: 8 value: 3
>>> 
This would be considered non-pythonic because it is not the most readable and compact implementation.

The former example using enumerate is most likely to get a thumbs up from fellow python developers but the later is probably going to give you a little bit of push back. I would prefer the enumerate implementation as well but because I have written a good number of C, COBOL, C++ and C# programs I don't judge either one as being good or bad. Its important to note that many developers are very good at looping through collections and they may not even see the benefit in the enumerate function.

The for in range structure  is still a useful construct and is needed if we want to:
  1. Iterate over a fixed number without indexing a collection. 
  2. Calling an internal or external API that gives us a count and a "get item" method instead of a collection.
  3. Skipping or "stepping" through index values.
Ranges can actually be saved into a variable, count backwards, step by positive and negative numbers and can be converted to other sequences like lists and tuples. The range function and xrange function are actually implemented differently and have a different processing cost. Even though their usage may be rare they do belong in python!

More on ranges can be found online here:
https://pynative.com/python-range-function/

A good book on python such as the one below can also be a valuable resource in learning python.

1 comment:

  1. Python | Gyansetu offers outstanding Python programming courses. The instructors are highly skilled, and the practical approach ensures rapid skill development. It's the perfect destination for mastering Python and enhancing your coding prowess!
    For more info:- https://www.gyansetu.in/blogs/future-scope-of-python-in-india/

    ReplyDelete

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...