InterviewSolution
| 1. |
What is the purpose of range( )? Explain with an example? |
|
Answer» (i) The range( ) is a function used to generate a series of values in Python. Using range( ) function, you can create list with series of values. The range( ) function has three arguments. Syntax of range( ) function: range (start value, end value, step value) where,
Example: Generating whole numbers upto 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 ( ) ) Note The list( ) function is all so used to create list in python. 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, Even _List list has the elements of first five even numbers. (iii) We can create any series of values using range( ) function. The following example explains how to create a list with squares of 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] |
|