Wednesday, March 20, 2019

A common mistake that people make with Python

A common mistake that people coming from other languages seem to make with Python is to rely on indexing into sequences when looping over them, instead of just looping over the sequence elements themselves (or using enumerate() when they do want indices).
As an example, a commonly seen pattern for Python beginners is:
  1. some_list = [‘a’, b’, c’, d’]
  2. for i in range(len(some_list)):
  3. print(some_list[i])
This is a simple example, but often they get more complicated with nested loops, or indexing by key into dictionaries instead of using the .items() call, etc. In Python, it is fairly rare to need a “range(len(x))” construct. A better way of doing this is simply:
  1. for v in some_list:
  2. print(v)
I.e. just iterate over the values of the list, or sequence. And be aware that there are other alternatives to looping over just indices, and be on the lookout for such examples while learning.
Another recommendation for people learning Python is to learn about sets and how powerful they can be. I see a fair amount of code that could be simplified by understanding and using set operations, which the language provides for you. I think with set literals it’s now becoming more common, but for a while it seemed like an underused Python type.
Share:

0 comments:

Post a Comment