#mastery25 Creation and use of ranges in Python

The range() Function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions, e.g.:

 

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The given end point is never part of the generated list; range(10) generates a list of 10 values, exactly the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative):

 

>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]

To iterate over the indices of a sequence, combine range() and len() as follows:

 

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print i, a[i]
... 
0 Mary
1 had
2 a
3 little
4 lamb

My example:

x=[‘mastery25′,’tc1014’]

for i in range (len(x)):

     print (“#”,x[i])

>>>25

>>>1014

25

1014

GILBERTO ROGEL GARCÍA

SOURCE: Here

CC BY 4.0 #mastery25 Creation and use of ranges in Python by Gilberto Rogel García is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.