June 2017
Beginner
352 pages
8h 39m
English
At this point we're going to show you another example of poorly styled code, except this time it's one you can, and should, avoid. Here's a poor way to print the elements in a list:
>>> s = [0, 1, 4, 6, 13]>>> for i in range(len(s)):... print(s[i])...014613
Although this works, it is most definitely unPythonic. Always prefer to use iteration over objects themselves:
>>> s = [0, 1, 4, 6, 13]>>> for v in s:... print(v)014613
If you need a counter, you should use the built-in enumerate() function which returns an iterable series of pairs, each pair being a tuple. The first element of each pair is the index of the current item and the second element of each pair is the item itself:
>>> t = [6, 372, 8862, 148800, 2096886] ...
Read now
Unlock full access