With Python being their “foreign” language, they may not have a systematic training on Python coding, and might not know the idiomatic way for their Python development. But don’t get me wrong — they can still write excellent code by implementing the same functionalities in different ways, as long as the code can satisfy the intended purposes. Thus, to me, it’s acceptable to write non-idiomatic Python programs.
However, just like I’m always working to improve my English accent as a foreigner in the United States, I want my Python code to be idiomatic as much as possible. In this article, I’m sharing some idiomatic usages that I have accumulated over the last several years, which I hope will help level up your Python coding.
1. Slice a Sequence
Some common sequence types are lists, tuples, and strings. We can create a sequence by slicing another sequence. The following functionalities use a list as an example, but they can also apply to tuples, strings, and other sequence types (e.g., bytes).
>>> a = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] >>> # Using a range, [start, end) >>> a[1:3] [2, 4] >>> # Using a range with a step >>> a[1:9:2] [2, 6, 10, 14] >>> # Leave out the start = an implicit start of 0 >>> a[:5] [0, 2, 4, 6, 8] >>> # Leave out the stop = an implicit end to the very last item >>> a[9:] [18, 20] >>> # Entire list >>> a[:] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]