Not using range: enumerate()

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])
...
0
1
4
6
13

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)
0
1
4
6
13

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]
>>> for p in enumerate(t):
>>> print(p)
(0, 6)
(1, 372)
(2, 8862)
(3, 148800)
(4, 2096886)

Even better, we can use tuple unpacking and avoid having to directly deal with the tuple:

>>> for i, v in enumerate(t):
... print("i = {}, v = {}".format(i, v))
...
i = 0, v = 6
i = 1, v = 372
i = 2, v = 8862
i = 3, v = 148800
i = 4, v = 2096886
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset