# Python for loop with Range function

In this tutorial, we will learn more about range functions and the most commonly used range functions in the for loop. So, after discussing the range function in detail, we will discuss the range function with the python for loop.

Suppose you are asked to display 1 to 10 integer sequences. Then if you don’t know the concept of range() or for loop then you can complete this task with print() function. For example

But this same task you can do very easily through the range function. Thus, the range function will provide you the specified integer sequence. This range function will return a range object when an argument is passed within the range function. And this range object will always be in the form of a sequence of numbers.

You can generate different types of sequences. But it will depend on the user how many arguments are passing and how many differences there are between each number in the sequence. So, according to this argument, we will divide the range function into three parts.

• Range (stop Argument)
• Range (start Argument, stop Argument)
• Range (start Argument, stop Argument, step Argument)

## Range (stop)

When only one argument is passed between the range functions, you need to use the stop argument.

Since the start argument is not used here, the number sequence will always start from zero and end with the previous number in the stop argument. And 1 will be different in each number of the sequence. You cannot use a negative number for an only stop argument.

So, look at the syntax of the stop argument with the range function below

## Range (start, stop)

Here, two arguments have been passed between the range functions. And when the range function returns the sequence of numbers, it will start with the start argument and end with the integer number before the stop argument.

Cannot use a negative value for both start and stop arguments. Here the interval between each number of the sequence will be 1. And the sequence will always start from the start argument and not from zero. If you give the value zero of the start argument then that is different.

So, look at the syntax of the range function with both start and stop arguments below.

## Range (start, stop, step)

Notice the two syntax above. Here, the interval between each number in the sequence is one. So, many times you should have a specified number interval between each number in the sequence.

If you want to take one or more intervals between each element of the sequence, you need to pass the step argument between the range functions. You don’t just have to use step arguments here, you also have to use both start and stop arguments. And you can take the value of the Start and Step argument in negative here.

Thus, the range object that the range function will return will start with the start argument and end with the previous element of the stop argument. And there will be a specified interval between each element of the range object.

Notice the syntax of the step argument with the range function which is mentioned below.

If you look at this three syntax above, you will understand that the stop argument is compulsory for range function. And the other two arguments are optional.

## reverse range

Many times you may have to print the elements of the range object in descending order or reverse order. We can solve this problem in three ways.

First, you can use the negative step value in the range function to print the elements of the sequence in descending order. In this case you need to take the value of the start argument greater than the value of the stop argument. And the value of the stop argument will always be negative here. So, look at this problem below.

range_list1 = range(10,0,-2)
print(list(range_list1))

range_list2 = range(10,0,-3)
print(list(range_list2))

range_list3 = range(0,-10,-2)
print(set(range_list3))

Output :

[10, 8, 6, 4, 2]
[10, 7, 4, 1]
{0, -8, -6, -4, -2}

Second, you can use the reverse() function to access the elements of the sequence in reverse order. In this case, the reverse function will return a range-iterator.

range_list1 = reversed(range(5))
print(list(range_list1))

range_list2 = reversed(range(10,15))
print(list(range_list2))

range_list3 = reversed(range(1,10))
print(tuple(range_list3))

Output :

[4, 3, 2, 1, 0]
[14, 13, 12, 11, 10]
(9, 8, 7, 6, 5, 4, 3, 2, 1)

Here the reverse sequence is the iterator so you can access the elements of the sequence in reverse order by using this reverse sequence directly for loop. Using this reverse sequence in the next function you can access the elements.

range_sequence = reversed(range(5))
print(type(range_sequence))
print(next(range_sequence))
print(next(range_sequence))
print(next(range_sequence))
print(next(range_sequence))
print(next(range_sequence))

Output :

<class 'range_iterator'>
4
3
2
1
0

Third, you can convert a range sequence into a reverse sequence by indexing. So, you can understand by looking at this example below.

range_list1 = range(5)[::-1]
print(list(range_list1))

range_list2 = range(10,15)[::-1]
print(list(range_list2))

range_tuple = range(1,10)[::-1]
print(tuple(range_tuple))

Output :

[4, 3, 2, 1, 0]
[14, 13, 12, 11, 10]
(9, 8, 7, 6, 5, 4, 3, 2, 1)

## Accessing range() with index value

This range function will return a range object to you when you pass an argument within the range function. Notice that each element of this range object is arranged according to the specified sequence.

range_list1 = range(10)[8:9]
print(list(range_list1))

range_list = range(5)[1:5]
print(list(range_list))

range_list = range(10)[::-1]
print(list(range_list))

Output :

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

So, for this you can access every element of the range object according to the index. Here you can use both positive and negative indexing.

## Concatenation of two range() functions

Here you can concatenate two range functions. For this, you need to import the itertools module because the chain function is present in this module which concatenates two range objects.

from itertools import chain
range_list = chain(range(1,5),range(0,10,2))
print(type(range_list))
print(list(range_list))

Output :

<class 'itertools.chain'>
[1, 2, 3, 4, 0, 2, 4, 6, 8]

## Using float Numbers in Python arange() :

The range function does not support floating-point numbers. Thus, you cannot use a non-integer number as an argument. You should always use integer numbers as arguments. You can look at the example below. The floating-point number has been used here as an argument. So, here you will see type error as output.

for var in range(0,4,.5):
print(var)

Output :

    for var in range(0,4,.5):
TypeError: 'float' object cannot be interpreted as an integer

You must use the Python NumPy module to generate a range of floating-point numbers. This is because the arange() function is present in the NumPy module which acts as the normal range function of Python.

Here you can use a floating-point number as an argument in arange() function or just use a floating-point number as step argument in both cases the sequence of floating-point numbers will return.

import numpy as np
print(np.arange(1, 5, 0.5))

Output :

[ 1.   1.5  2.   2.5  3.   3.5  4.   4.5]

You can also create a sequence of floating-point numbers in a variety of ways using generator or yard keywords.

## Convert range object to another data type

You can convert range objects to different data types such as lists, tuples, sets, and dictionaries, etc.

### 1. Convert range object to List :

To convert a range object to a list, you need to use the list() function in which the range function is passed. And this list function will return a list of sequence numbers. For example

range_list = list(range(5,10))
print(range_list)

range_list = list(range(5))
print(range_list)

range_list = list(range(0,10,2))
print(range_list)

Output :

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

### 2. Convert range object to Tuple and set :

Similarly, to convert a range object to the tuple and set, you need to use the tuple() and set() functions. And when you convert a range object to a set, the elements in the set will not be arranged in the specified order because set is the collection of unordered elements. For example

range_list = tuple(range(5))
print(range_list)

range_list = set(range(0,10,2))
print(range_list)

Output :

(0, 1, 2, 3, 4)
{0, 2, 4, 6, 8}

### 3. Convert range object to the dictionary :

Here you can convert the range object to a dictionary but for this you need to use the zip() function. Because a dictionary is made up of a combination of key and value.

range_list = dict(zip(range(5),range(0,10,2)))
print(range_list)

range_list = dict(zip(range(5),range(7)))
print(range_list)

range_list = dict(zip())
print(range_list)

Output :

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
{}

So, in the zip() function you have to pass two range functions so that the elements of the first range object will act as the key and the elements of the second range object will perform as the value.

## Python For loop with range Function

Python’s range function may seem like an iterator to many people but it is not an iterator. Thus, you cannot access each element of the range object one by one with the next() function.

int_sequence = range(1,5)
print(next(int_sequence))
print(next(int_sequence))
print(next(int_sequence))
print(next(int_sequence))

Output :

TypeError: 'range' object is not an iterator

Because range is an iterable object i.e. range object will be converted to iterator first and then one by one the elements will be accessed by the next function.

int_sequence = iter(range(1,5))
print(next(int_sequence))
print(next(int_sequence))
print(next(int_sequence))
print(next(int_sequence))

Output :

1
2
3
4

Of course, you have seen in a practical way that the range function is iterable, that is, its elements are arranged in order. For this you can use the range function directly with the for loop.

## Python for loop with range function examples

So, Below we will look at fifty problems related to Python for Loop with Range function and how they have been solved.

1. How do you print each element of the range on the same line.

for var in range(10):
print(var,end='  ')

Output :

0  1  2  3  4  5  6  7  8  9

Here you need to pass end=' ' in the print function.

2. How do you print each element of the sequence on the same line that will be separated by commas.

for var in range(10):
print(var,end=' , ')

Output :

0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,

In this case you have to pass a comma in the end=().

3. How do you print a sequence of even numbers using a range function.

for var in range(10):
if var%2 ==0:
print(var)

Output :

0
2
4
6
8

In this case you have to apply the condition and check whether the number is even or not. So, if the number is an event, print it.

4. How do you create a sequence of odd numbers.

for var in range(10,20):
if var%2 !=0:
print(var)

Output :

11
13
15
17
19

Notice the problem just above. This is how you solve this problem.

5. How do you make a right angel triangle. Where the odd line will be filled with * and the even line will be filled with #.

for var in range(7):
if var%2 !=0:
print(' *'* var)
else:
print(' #'* var)

Output :

 *
# #
* * *
# # # #
* * * * *
# # # # # #

Here also you have to apply if-else condition. And it needs to be filled with odd line * and even line #.

6. How do you create the English letter k shape by * and # ?

for var in range(5,-6,-1):
if var >1 :
print('* '*var)
elif var ==0:
print('*')
elif var<-1:
print('* '*(-var))

Output :

* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *

7. How to print each element of the list according to its position without enm() function?

companies = ['Google', 'Adobe', 'Amazone', 'Fb']
for var in range(len(companies)):
print(f'index {var} ----> company {companies[var]}')

Output :

index 0 ----> company Google
index 2 ----> company Amazone
index 3 ----> company Fb

Here we have used f string formatting.

8. How do you create a new list with input from the user using Python for Loop?

companies = []
for var in range(3):
companies.append(input())
print(companies, end= ' ')

Output :

google
amazon
['google', 'facebook', 'amazon']

Here you can take input from the user three times because the body of the for loop will be executed three times. No type function has been used before the input() function used in the append() function. So, whatever input you give will be acceptable as a string to Python Interpreter.

9. How do you create a separate list by taking the elements of another list in opposite directions?

companies1 = []
for var in reversed(range(len(companies))):
companies1.append(companies[var])
print(companies1)

Output :

['fb', 'amazone', 'adobe', 'google']

In this case you have to pass each element of the list in the append() function.

10. How to create a new 1d list with the elements of a 2d list.

number_list = [ [12], [34,56], [21,59,100]]
number_list1 = []
for i in range(len(number_list)):
for j in number_list[i] :
number_list1.append(j)
print(number_list1)

Output :

[12, 34, 56, 21, 59, 100]

You need to use Nested python for Loop to access the 2d list elements.

## FAQ’s

What is the range function?

Range is a Python library function that returns a sequence of integer numbers to you.

How can you pass an argument within a range function?

You can pass arguments in a range function in three different ways.

• Range (stop Argument)
• Range (start Argument, stop Argument)
• Range (start Argument, stop Argument, step Argument)

The reverse object is an iterator! But it seems like an iterable object.

Yes, the reverse object looks like an iterable object but it is an iterator. You look at this problem below.

var = reversed(range(5))
print(next(var))
print(next(var))
print(next(var))
print(next(var))
print(next(var))

Output :

4
3
2
1
0

So, you can access every element of the reverse object with the help of next() function.

Can you create a float sequence with the range function? If not, what is the different process.

No, the range function will only provide you integer sequences. And because of this limitation you cannot pass any float number as an argument in the range function.

for var in range(0,10,.5):
print(var)

Output :

  for var in range(0,10,.5):
TypeError: 'float' object cannot be interpreted as an integer

If you really want to work with a float number sequence, you can use the arange() function which is located in the NumPy package.

How do you convert a range sequence to another data type?

You can convert range sequences to different data types. Such as list, set, tuple, duct etc. For this you need to use type convert function like list for list() function. In the same way, each data type has specific functions to convert such as set(), tuple(), dict(), str() etc. Notice the program below.

var = range(5)
print(list(var))
print(tuple(var))
print(set(var))
print(dict(zip(var,range(5,10))))

Output :

[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)
{0, 1, 2, 3, 4}
{0: 5, 1: 6, 2: 7, 3: 8, 4: 9}

How You Can Concatenation Between Two Range Functions?

You will need the help of the itertools module for the Concatenation of two range functions. And in the chain function you have to pass two range objects which will convert and return you a range object.

from itertools import chain
range_list = chain(range(1,5),range(0,10,2))
range_list1 = chain(range(-5,0),range(0,10,2))
print(range_list)
print(list(range_list))
print(tuple(range_list1))

Output :

<itertools.chain object at 0x0153B070>
[1, 2, 3, 4, 0, 2, 4, 6, 8]
(-5, -4, -3, -2, -1, 0, 2, 4, 6, 8)

## Conclusion

Most of the time we will notice that Python for Loop is used with the range function. For this reason, in this tutorial, we have discussed in detail about Python for loop with range function. And here enough problems have been solved to clear each concept. If you think this content is valuable, don’t forget to share and comment.