Tags
python
Asked 2 years ago
5 Aug 2021
Views 205
Letitia

Letitia posted

What is Range function in Python ?

What is Range function in Python ?
sachin

sachin
answered Aug 8 '21 00:00

range() is function which generate range list in Python
syntax :
range(start,stop, step)
range generate the range between start and stop , with step duration

suppose range(1,10) generate 1 to 10 range , here step is 1 by default if it not passed anything for step(last argument), it will increament each by 1

print(list(range(1,10)))


it will print

[1, 2, 3, 4, 5, 6, 7, 8, 9]


lest just check with for loop how it goes with range()


for i in range(1,10):
	print(i)

it will print 1 to 9

1
2
3
4
5
6
7
8
9


lets play with step ,
range(1,10,2) i put step is 2 so it increase by 2 for each step

for i in range(1,10,2):
	print(i)

so now print is like this

1
3
5
7
9

you can see the each number printed is increase by 3

is that possible we can print the reverse number with range() function ?

Yes it is see below code

for i in range(10,1,-1):
	print(i)

it will increment each step by -1 and we provided stat value is 10 so it goes like 10-1=9 , 8... etc
so it will output like this :

10
9
8
7
6
5
4
3
2
Post Answer