Friday 4 December 2015

Python: range function

‘range()’ function is used to iterate over a sequence of numbers.

There are two variants of range function.
class range(stop)
class range(start, stop[, step])

All the arguments to range function are integers. By default start is assigned to 0, step is assigned to 1. ‘range(5) is same as ‘range(0, 5).


test.py
for i in range(5):
 print(i)

$ python3 test.py
0
1
2
3
4


test.py
for i in range(0, 15, 3):
 print(i)


$ python3 test.py
0
3
6
9
12

If you assign 0 to the argument ‘step’ then ValueError thrown.

test.py

for i in range(0, 15, 0):
 print(i)


$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    for i in range(0, 15, 0):
ValueError: range() arg 3 must not be zero

test.py

for i in range(0, -10, -2):
 print(i)


$ python3 test.py
0
-2
-4
-6
-8

Check for a value in given range
By using ‘in’ operator you can check, whether given value is in range or not.

>>> 2 in range(0, 10, 2)
True
>>> 4 in range(0, 10, 2)
True
>>> 14 in range(0, 10, 2)
False
>>> 1 in range(0, 10, 2)
False


By using range(), len() functions, you can iterate over a sequence.

test.py

names=["Phalgun", "Sambith", "Mahesh", "swapna"]

for i in range(len(names)):
 print(i, names[i])
else:
 print("Exiting from loop")

print("Execution finished")


$ python3 test.py
0 Phalgun
1 Sambith
2 Mahesh
3 swapna
Exiting from loop
Execution finished

Note:
For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.



Previous                                                 Next                                                 Home

No comments:

Post a Comment