I have a set of numbers and I don't want to print all the numbers separateley.How does python's range function can help me?
Mar 31, 2018 in Python 122 views

You can use a range function whenever you want to run a piece of code more than once. You can use "for" loop. Look at the below example:

```fruits = ['Banana', 'Apple',  'Grapes']

for index in range(len(fruits)):

print (fruits[index])```

Notice here, we have specified the range, that means we know the number of times the code block will be executed.

Output:

```Banana

Apple

Grapes```
• 6,850 points

The range function is mostly used in for-loop.

Ex:

```for i in range(0,5):

print(i)```

The output will be:

```0

1

2

3

4```

Note: When you use the range() function, the 2nd parameter is excluded in the range.

• 69,000 points
+1 vote

range(x) returns a list of numbers from 0 to x - 1.

```>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]```

for i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range(). i is used inside the body to refer to the “current” item of the list. In that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.

• 4,770 points
+1 vote
```>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]```
answered Oct 12, 2018 by abc
+1 vote
```# You can use range() wherever you would use a list.

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

for a in range(21,-1,-2):
print a

#output>> 21 19 17 15 13 11 9 7 5 3 1```
answered Oct 12, 2018 by rani
+1 vote
```# We can use any size of step (here 2)
>>> range(0,20,2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> range(20,0,-2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]```
answered Oct 12, 2018 by kalpesh
+1 vote
```# The sequence will start at 0 by default.
#If we only give one number for a range this replaces the end of range value.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]```
answered Oct 12, 2018 by Karunesh
+1 vote
```# If we give floats these will first be reduced to integers.
>>> range(-3.5,9.8)
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]```
answered Oct 12, 2018 by rajiv

How can I use the power function in python 2.7?

print(pow(3,4)) #this will return the exponentiation of 3 ...READ MORE

how can i use the sum function in a python list?

to calculate the sum of all the ...READ MORE

How can I use the sleep function in a python program?

Can you give a sample code for ...READ MORE

How can I build a recursive function in python?

I'm wondering whether you meant "recursive". Here ...READ MORE

+1 vote

How can I use python to execute a curl command?

For sake of simplicity, maybe you should ...READ MORE

how do i change string to a list?

suppose you have a string with a ...READ MORE

+1 vote

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE