banner



Python Print Sequence Of Numbers

Python range() function generates the immutable sequence of numbers starting from the given start integer to the stop integer. The range() is a born function that returns a range object that consists series of integer numbers, which we can iterate using a for loop.

In Python, Using a for loop with range(), nosotros tin can repeat an action a specific number of times. For example, let's see how to use the range() part of Python three to produce the beginning half-dozen numbers.

Instance

            # Generate numbers between 0 to 6 for i in range(6):     impress(i)          
python range() function
Python range() office

Notation: As you can see in the output, Nosotros got six integers starting from 0 to 5. If you notice, range() didn't include 6 in its result because it generates numbers up to the stop number but never includes the stop number in its result.

The range() works differently between Python 3 and Python 2.

See range() in Python two

  • In Python two, we takerange() andxrange() functions to produce a sequence of numbers.
  • In Python 3xrange() is renamed torange() and originalrange() function was removed. We will discuss information technology in the later section of the article.

Tabular array of contents

  • How to use range() function in Python
    • Syntax
    • Parameters
    • Return Value
    • Steps to use range() function
  • range() Examples
    • range(stop)
    • range(start, terminate)
    • range(start, stop, pace)
    • Points to recall about range() function
  • for loop with range()
    • Iterate a list using range() and for loop
    • Do Problem
  • Contrary range
    • Using negative step
    • Using reversed() part
    • Use range() to reverse a listing
  • Python range footstep
    • Decrementing range() using step
  • Negative range() in Python
  • Catechumen range() to listing
  • Inclusive range
  • range() vs. xrange() in Python 2
  • Concatenating the result of two range()
  • range() indexing and slicing
  • range() over graphic symbol or alphabet
  • Summary
  • FAQ

How to employ range() office in Python

Syntax

Below is the syntax of the range() office.

            range(start, end[, pace])          

It takes three arguments. Out of the three, 2 are optional. The start and stride are optional arguments and the stop is the mandatory argument.

Parameters

  • start: (Lower limit) It is the starting position of the sequence. The default value is 0 if not specified. For instance, range(0, 10). Here, outset=0 and stop = ten
  • terminate: (Upper limit) generate numbers up to this number, i.e., An integer number specifying at which position to stop (upper limit). The range() never includes the stop number in its result
  • pace: Specify the increment value. Each adjacent number in the sequence is generated by adding the step value to a preceding number. The default value is 1 if not specified. It is naught simply a deviation between each number in the result. For instance, range(0, 6, ane). Hither, step = 1.

Return Value

It returns the object of class range.

            print(type(range(10))) # Output <class 'range'>          

Steps to use range() office

The range() part generates a sequence of integer numbers equally per the argument passed. The below steps show how to use the range() function in Python.

  1. Pass start and stop values to range()

    For instance, range(0, six). Here, start=0 and terminate = half dozen. It will generate integers starting from the start number to stop -i. i.e., [0, 1, ii, 3, 4, 5]

  2. Laissez passer the pace value to range()

    The step Specify the increase. For example, range(0, 6, 2). Here, step = 2. Result is [0, 2, 4]

  3. Use for loop to access each number

    Use for loop to iterate and access a sequence of numbers returned by a range().

steps to use python range() function
Steps to use range()

range() Examples

Now, let'due south come across all the possible scenarios. Below are the three variants of range().

range(terminate)

When you pass just i argument to the range(), it will generate a sequence of integers starting from 0 to cease -ane.

            # Print outset ten numbers  # terminate = 10 for i in range(ten):     print(i, end=' ')  # Output 0 one 2 3 4 five 6 seven 8 9          

Note:

  • Here, start = 0 and step = 1 every bit a default value.
  • If y'all set up the stop as a 0 or some negative value, then the range will render an empty sequence.
  • If yous want to outset the range at one use range(1, ten).

range(starting time, finish)

When you pass two arguments to the range(), it will generate integers starting from the start number to stop -1.

            # Numbers from 10 to 15 # get-go = ten # stop = sixteen for i in range(x, sixteen):     print(i, terminate=' ')  # Output 10 11 12 thirteen xiv 15          

Note

  • Here, the step = ane as a default value.
  • The range will return an empty sequence if yous set the cease value lesser than the start.

range(start, stop, step)

When you laissez passer all three arguments to the range(), it will return a sequence of numbers, starting from the commencement number, increments by pace number, and stops earlier a stop number.

Here you can specify a dissimilar increment by adding a step parameter.

            # Numbers from ten to 15 # start = 10 # stop = 50 # pace = 5 for i in range(10, fifty, 5):     impress(i, end=' ')  # Output 10 15 20 25 30 35 xl 45          

Notation:

  • Here, the pace = 0 every bit a default value.
  • Python will raise a ValueError exception if you lot set up the step to 0.

Points to remember about range() function

  • The range() function just works with the integers, So all arguments must exist integers. Yous can non use float numbers or any other data blazon as a start, stop, and step value. Please refer to generate a range of float numbers in Python
  • All iii arguments can exist positive or negative.
  • The step value must non be goose egg. If a pace=0, Python volition raise a ValueError exception.

Practice Problem: –

Userange() to generate a sequence of numbers starting from 9 to 100 divisible by iii.

Show Solution
                    # start = 9 # finish = 100 # step = three (increment) for i in range(9, 100, 3):     impress(i)                                      

See: Python for loop and range() practice

for loop with range()

Python for loop executes a block of lawmaking or statement repeatedly for a fixed number of times. Nosotros tin iterate over a sequence of numbers produced by the range() role using for loop.

Permit's see how to use for loop with range() role to print the odd numbers between i and 10. Using this example, nosotros can empathize how the iterator variable i is getting value when we employ range() with for loop.

            for i in range(1, 10, 2):     print("Electric current value of i is:", i)          

Output

Electric current value of i is: 3 Current value of i is: 5 Electric current value of i is: seven Electric current value of i is: 9

To understand what for i in range() means in Python, we demand first to understand the working of the range() function.

The range() office uses the generator to produce numbers. It doesn't generate all numbers at in one case.

As you lot know range() returns the range object. A range object uses the same (pocket-size) amount of memory, no matter the size of the range information technology represents. It but stores the start, stop and step values and calculates individual items and subranges as needed.

I.e., It generates the next value just when for loop iteration asked for it. In each loop iteration, Information technology generates the adjacent value and assigns it to the iterator variable i.

  • As you can see in the output, the variable i is not getting the values 1, 3, v, 7, and 9 simultaneously.
  • In the first iteration of the loop value of i is the commencement number of a range.
  • Next, In every subsequent iteration of for loop, the value of i is incremented by the step value. The value of i is determined by the formula i = i + step.

And then it ways range() produces numbers one past one as the loop moves to the side by side iteration. It saves lots of retentivity, which makes range() faster and more than efficient.

Working of Python range function with for loop
Working of Python range function with for loop

Iterate a list using range() and for loop

You can iterate Python sequence types such as listing and string using a range() and for loop.

When you iterate the listing only using a loop, you tin access but items. When you lot iterate the list only using a loop, you can only access its items, but when you lot utilize range() forth with the loop, you lot tin can access the index number of each particular.

The advantage of using range() to iterate a list is that it allows u.s.a. to access each item's index number. Using alphabetize numbers, we tin can access as well as modify list items if required.

Example

Pass the count of total list items to range() using a len() function. The range() volition apply information technology every bit a stop statement.

            list1 = ['Jessa', 'Emma', 20, 30, 75.5] # iterate a list using range() for i in range(len(list1)):     print(list1[i])          

Output:

Jessa Emma 20 30 75.v

Practise Problem

Print the post-obit number pattern using Pythonrange() and a loop.

1  2 2  3 3 iii            
Bear witness Solution
                    for num in range(4):     for i in range(num):         print(num, end=" ")     impress()  # new line after each row to prove design correctly                                      

Read More:

  • Python for loop and range() Do

Contrary range

You can display the sequence of numbers produced by a range() function by descending lodge or reverse order.

You can use the following two ways to get the opposite range of numbers in Python.

  • Use a negative pace value
  • Employ a reversed() part
Python reverse range

Using negative pace

Employ a negative step value in a range() function to generate the sequence of numbers in contrary order. For example, range(v, -,i, -1) will produce numbers like 5, four, three, 2, and 1.

I.e., y'all can reverse a loop past setting the stride argument of a range() to -ane. It volition cause the for loop to iterate in reverse club.

Let's run across how to loop in a reverse iteration or backward iteration to display a range of numbers from 5 to 0.

            # contrary range using negative pace # showtime = v # terminate = -1 # step = -1 for i in range(v, -1, -1):     print(i)          

Output:

5 four 3 2 1 0

Using reversed() function

Using Python'south built-in reversed() function, you can opposite any sequence such equally listing or range.

  • Pass the range() as an input to the reversed() function, Information technology returns a range_iterator that accesses the sequence of numbers provided by range() in the reverse order.
  • Adjacent, iterate the event provided by reversed() part using for loop.

Example 2: contrary range starting from twenty to ten

            for i in reversed(range(x, 21)):     impress(i, end=' ') # Output 19 xviii 17 sixteen 15 14 thirteen 12 11 x          

Example three: reverse range starting from 20 to 10 with footstep 2

            for i in reversed(range(10, 21, 2)):     print(i, terminate=' ') # Output 20 18 sixteen fourteen 12 10          

Notation: The reversed(range(n)) returns a range_iterator that accesses the sequence of numbers provided by range() in the reverse guild.

            print(blazon(range(0, 5))) # Output <class 'range'>  impress(type(reversed(range(0, 5)))) # Output <class 'range_iterator'>          

Likewise, If you demand the list out of it, you need to convert the output of the reversed() function to list. Then you can get the contrary list of ranges.

Use range() to reverse a listing

Apply range() to contrary a listing past passing the count of list items as a start statement and step as a -1.

Let'southward see the various ways to reverse a list of numbers using a range()

            list1 = [x, 20, xxx, forty, 50] # start = listing'southward size # stop = -1 # step = -i  # reverse a list for i in range(len(list1) - 1, -1, -1):     print(list1[i], end=" ") # Output l twoscore 30 20 10                      

Python range step

A stride is an optional argument of a range(). It is an integer number that determines the increment between each number in the sequence. i.e., It specifies the incrementation.

You can also define information technology equally a difference between each preceding and next number in the consequence sequence. For example, If the pace is 2, and then the difference between each preceding and post-obit number is 2

The default value of the step is 1 if non specified explicitly.

Example: Increment using step

            # range() footstep with default value for i in range(10):     impress(i, terminate=' ') # Output 0 1 two 3 four v half dozen seven 8 9  # Increment in range() with pace = 2 # impress table of 2 using range() for i in range(two, 22, 2):     print(i, end=' ') # Output 2 4 6 8 10 12 fourteen 16 18 xx                      

You tin also perform lots of operations by using step arguments such as reverse a sequence such as a list and string.

Decrementing range() using step

You tin decrement range() by using negative stride value.

When nosotros set the negative value to step, In each iteration, the number will go downwardly until it reaches to end number.

            # Decrement range() using footstep # start = thirty, stop = 20 # step = -ii for i in range(xxx, twenty, -2):     print(i, end=' ') # Output 30 28 26 24 22                      

Notation: To decrement range() the start must be greater than stop. A range() return empty sequence if showtime < terminate.

            for i in range(xx, 30, -2):     print(i, cease=' ')          

Besides, you can use stride to generate sequence of numbers multiply of northward.

            # Generate integers multiply by 7 for i in range(7, 77, vii):     print(i, end=' ') # Output 7 fourteen 21 28 35 42 49 56 63 70          

Also, you will get a valueerror if you set step = 0.

            for i in range(1, 5, 0):     print(i, end=' ') # Output ValueError: range() arg 3 must not exist naught                      

Besides, you can't use the decimal step value. If you lot want to use the float/decimal step in the range(), please refer to generating a range of bladder numbers.

Negative range() in Python

You can utilise negative integers in range().

Most of the time, nosotros use the negative footstep value to reverse a range. But autonomously from the step, nosotros can utilize negative values in the other two arguments (start and stop) of a range() function.

Instance: Negative range from -1 to -ten

Let'due south see the example to print the range of numbers from negative to positive.

            # negative range from -ane to -ten for i in range(-1, -eleven, -ane):     print(i, end=', ') # Output -ane, -2, -3, -4, -5, -vi, -7, -8, -ix, -ten          

Let's understand the above program, nosotros set up –

  • starting time = -ane (because nosotros wanted to starting time producing number from -ane)
  • stop = -11 (We want to finish generating numbers when nosotros reach -eleven)
  • footstep = -1

Execution:

  • In the 1st iteration of the loop, i is -ane
  • In the 2d iteration of for loop, i is -two because -1+(-1) = -2, and information technology will repeat this process till the cease number.

Example: Negative opposite range from -10 to -one

You lot can also impress the negative reverse range() using a positive footstep integer.

            # negative range from -10 to -ane # kickoff = -10 # stop = 0 # stride = ane for i in range(-10, 0):     print(i, end=', ') # Output -10, -nine, -8, -7, -6, -5, -4, -3, -ii, -i,          

Combination of negative and positive numbers

            # stat = 2, stop = -5, step = -1 for i in range(two, -five, -ane):     print(i, end=", ") # Output 2, 1, 0, -1, -2, -iii, -4,          

Convert range() to list

Python range() office doesn't return a listing type. It returns an immutable sequence of integers.

We tin convert range() to listing using a list() constructor.

  • Laissez passer the range() function as an input to the list constructor.
  • The listing() constructor automatically creates a list past enclosing the integers returned by the range() inside the foursquare brackets.
            # create list from range() sample_list = listing(range(2, ten, 2)) impress(type(sample_list)) # Output <class 'listing'>  # brandish listing print(sample_list) # Output [2, 4, 6, 8]  # iterate list for item in sample_list:     print(item)                      

Access and alter list detail using range()

Too, yous tin use range() to admission and change listing items.

  • Using a len() function, yous can get a count of list items.
  • Next, utilize this count as a cease number in range() and iterate for loop end-1 times.
  • In each iteration, you will go the index number of a current list item.
            # create listing from range() sample_list = listing(range(10, 100, 10))  # iterate and modify list item using range() # double each list number # get-go = 0, stop = list size, footstep =1 for i in range(0, len(sample_list), ane):     sample_list[i] = sample_list[i] * 2  #  brandish updated listing impress(sample_list) # Output [twenty, 40, lx, eighty, 100, 120, 140, 160, 180]          

Inclusive range

In this section, we will acquire how to generate an inclusive range in Python. Past default, The range(n) is exclusive, then it doesn't include the last number in the consequence. It creates the sequence of numbers from start to stop -ane.

For case, range(five) volition produce [0, one, two, 3, iv]. The outcome contains numbers from 0 to upwardly to 5 merely not five.

If you observe, the effect contains 5 elements which equal to len(range(0, 5)). Note, the index always starts from 0, not 1.

If you lot want to include the finish number in the event, i.east., If you want to create an inclusive range, and then set the finish statement value every bit stop+step .

Instance

            # inclusive range starting time = 1 stop = 5 pace = 1  # change stop stop += pace  for i in range(start, cease, step):     print(i, end=' ') # Output 1 2 three 4 v                      

Example 2: Even inclusive range()

            step = 2 for i in range(2, 20 + step, stride):     print(i, end=' ') # Output 2 4 6 8 ten 12 xiv 16 xviii 20          

range() vs. xrange() in Python 2

The range() vs xrange() comparison is relevant just if you are using Python 2 and Python three. If you are non using Python 2 you can skip this comparison.

The range() function works differently between Python 3 and Python 2. If your awarding runs on both Python 2 and Python 3, you must employ range() instead of xrange() for improve code compatibility.

In Python 2, nosotros have range() and xrange() functions to produce a sequence of numbers.

In Python 3 xrange() is renamed to range() and original range() function was removed.

So in simple terms, xrange() is removed from Python 3, and we tin can use only the range() part to produce the numbers within a given range.

Employ of range() and xrange()

  • In Python ii, range() returns the list object, i.e., Information technology does generate all numbers at once. The range(1, 500) will generate a Python listing of 499 integers in memory. So Information technology consumes high memory and increases the execution time.
  • xrange(): The xrange(1, 500) function doesn't generate all numbers at once. It produces numbers one by one as the loop moves to the adjacent number. So information technology consumes less memory and resources.

Instance

            print 'Python ii range' impress range(10) print type(range(ten))  print 'Python 2 xrange' for i in xrange(10):     print i  impress type(xrange(10))          

Output

Python 2 range() [0, 1, two, 3, 4, 5, six, 7, 8, 9] type 'list'  Python two xrange()  0  1  2  3  4  v  6  7  8  ix type 'xrange'

Concatenating the result of two range()

Permit say yous want to add range(5) + range(10,15). And you lot desire the concatenated range like[0, 1, 2, 3, four, 10, 11, 12, 13, 14].

For case, you want to add the result of two range() functions to produce another sequence of numbers. You lot can add/merge the consequence of multiple range() functions using itertools.chin().

            from itertools import chain  # Concatenate ranges new_range = chain(range(5), range(5, 10)) for num in new_range:     print(num, stop=' ') # Output 0 ane 2 three 4 5 vi 7 8 9          

range() indexing and slicing

Built-in function range() is the constructor that returns a range object, this range object tin can too be accessed past its index number using indexing and slicing.

Access range() attributes

Information technology is essential to know the range() attributes when you receive it as input to your office, and you lot wanted to see the value of the commencement, stop and pace argument.

            range1 = range(0, 10)  # admission range() attributes print(range1.start)  # 0 impress(range1.stop)  # 10 print(range1.stride)  # 1          

Indexing

range() supports both positive and negative indices. The below instance demonstrates the same.

In the case of range(), The index value starts from aught to (stop). For example, if you want to admission the third number, we demand to use 2 as the alphabetize number.

            range1 = range(0, 10)  # commencement number (commencement number) in range impress(range1[0])   # admission 5th number in range impress(range1[five]) # Output 5  # access last number impress(range1[range1.stop - 1]) # Output 9                      

Negative indexing

The numbers tin be accessed from right to left by using negative indexing.

            # negative indexing # access concluding number print(range(10)[-1]) # Output 9  # admission 2nd last number impress(range(10)[-2]) # Output eight          

Slicing

Slicing a implies accessing a portion from range()

            # slicing for i in range(ten)[3:8]:     impress(i, end=' ') # output 3 four 5 6 7          

range() over character or alphabet

Is at that place a style to print a range of characters or alphabets? For example similar this.

            for char in range ('a','z'):     print(char)          

Is there a way to print a range of characters or alphabets? For example like this. It is possible to create a range of characters using the custom generator. Permit's see how to generate the 'a' to 'z' alphabet using the custom range() function.

Annotation: We need to utilise the ASCII value and then convert the ASCII value to a letter using a Chr() function.

            # range from 'a' to 'z def character_range(char1, char2):     for char in range(ord(char1), ord(char2) + 1):         yield (char)   for letter in character_range('a', 'z'):     impress(chr(letter), end=', ')                      

Output

a, b, c, d, e, f, thou, h, i, j, chiliad, l, yard, n, o, p, q, r, s, t, u, five, due west, ten, y, z,          

Summary

I desire to hear from you. What exercise you lot think of this guide on Python range()? Let me know by leaving a annotate below.

Also, attempt to solve the Python loop Exercise and for loop Quiz.

Below is the summary of all operations that we learned in this lesson

Operation Description
range(cease) Generate a sequence of integers from zero to stop-ane
range(start, stop) Generate a sequence of integers from first to stop-1
range(start, stop, pace) Generate a sequence of integers starting from the start number, increments past pace, and stops before a stop number. I.e., Each next number is generated by adding the step value to a preceding number.
range(5, -1, -1) Reverse range
reversed(range(v)) Reverse range using a reversed() role
range(-i, -11, -1) Negative range from -one to -x
list(range(two, 10, 2)) Convert range() to list
range(start, stop+footstep, step) Generate an inclusive range
range(0, 10)[5] Access fifth number of a range() directly
range(10)[3:eight] Piece a range to access numbers from alphabetize iii to 8
range.start Get the showtime value of a range()
range.terminate Get the stop value of a range()
range.footstep Get the step value of a range()
Usage of Python range()

FAQ

Does range() in Python start at 0?

The range() by default starts at 0, non 1, if the start argument is non specified. For instance, range(5) will return 0, one, ii, 3, 4.

What does range() return in Python?

The range() function returns an object of class range, which is zip but a series of integer numbers.

Is range a listing in Python?

No. range() is not a listing, nor information technology returns a list type. A range() return range object. You tin can verify the data type of range() using the type(range(5)) function.

How practice you lot sum a range() in Python?

Use bulit-in function sum(). For instance, sum(range(10)

Python Print Sequence Of Numbers,

Source: https://pynative.com/python-range-function/

Posted by: pierrewasell.blogspot.com

0 Response to "Python Print Sequence Of Numbers"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel