Advertisements
Advertisements
Question
What is the purpose of range( )? Explain with an example.
Advertisements
Solution
(i) The range( ) is a function used to generate a series of values in Python. Using the range( ) function, you can create a list with series of values. The range( ) function has three arguments.
Syntax of range( ) function:
range (start value, end value, step value)
where,
- start value – beginning value of series. Zero is the default beginning value.
- end value – the upper limit of series. Python takes the ending value as upper limit – 1.
- step value – It is an optional argument, which is used to generate different intervals of values.
Example:
Generating whole numbers up to 10
for x in range (1, 11):
print(x)
Output:
1
2
3
4
5
6
7
8
9
10
(ii) Creating a list with series of values
Using the range( ) function, you can create a list with series of values. To convert the result of range( ) function into list, we need one more function called list( ). The list( ) function makes the result of range( ) as a list.
Syntax:
List_Varibale = list ( range ( ) )
Example
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
[2, 4, 6, 8, 10]
In the above code, list( ) function takes the result of range( ) as Even List elements. Thus, the Even _List list has the elements of the first five even numbers.
(iii) We can create any series of values using the range( ) function. The following example explains how to create a list with squares of the first 10 natural numbers.
Example: Generating squares of first 10 natural numbers
squares = [ ]
for x in range(1,11):
s = x ** 2
squares.append(s)
print (squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
APPEARS IN
RELATED QUESTIONS
Pick odd one in connection with collection data type?
Let list1 = [2,4,6,8,10], then print(List1[-2]) will result in ______
Which of the following function is used to count the number of elements in a list?
If List = [17,23,41,10] then List.append(32) will result ______
Which of the following statement is not correct?
Let setA = {3,6,9}, setB = {1,3,9}. What will be the result of the following snippet?
print(setA|setB)
Which of the following set operation includes all the elements that are in two sets but not the ones that are common to two sets?
What is a List in Python?
Explain the difference between del and clear( ) in the dictionary with an example.
What is the difference between List and Dictionary?
