InterviewSolution
| 1. |
What is a range object in Python? |
|
Answer» In Python, range is one of the built-in objects. It is an immutable sequence of integers between two numbers separated by a fixed interval. The range object is obtained from built-in range() function. The range() function has two signatures as follows: range(stop) range(start, stop[, step])The function can have one, two or three integer arguments named as start, stop and step respectively. It returns an object that produces a sequence of integers from start (inclusive) to stop (EXCLUSIVE) by step. In case only one ARGUMENT is given it is treated as stop value and start is 0 by default, step is 1 by default. >>> #this will result in range from 0 to 9 >>> range(10) range(0, 10)If it has two arguments, first is start and second is stop. Here step is 1 by default. >>> #this will return range of integers between 1 to 9 incremented by 1 >>> range(1,10) range(1, 10)If the function has three arguments, they will be used as start, stop and step parameters. The range will contain integers from start to step-1 separated by step. >>> #this will return range of odd numbers between 1 to 9 >>> range(1,10,2) range(1, 10, 2)Elements in the range object are not automatically displayed. You can cast range object to list or tuple. >>> r=range(1,10,2) >>> list(r) [1, 3, 5, 7, 9]The most common use of range is to TRAVERSE and process periodic sequence of integers using ‘for’ loop. The following statement produces the SQUARE of all numbers between 1 to 10. >>> for i in range(11): PRINT ('square of {} : {}'.format(i,i**2)) square of 0 : 0 square of 1 : 1 square of 2 : 4 square of 3 : 9 square of 4 : 16 square of 5 : 25 square of 6 : 36 square of 7 : 49 square of 8 : 64 square of 9 : 81 square of 10 : 100The range object has all methods available to a sequence, such as len(), index() and count() >>> r=range(1,10,2) >>> len(r) 5 >>> r.index(7) 3 >>> r.count(5) 1It is also possible to obtain an iterator out of the range object and traverse using next() function. >>> it=iter(r) >>> while True: try: print(next(it)) except StopIteration: break 1 3 5 7 9 |
|