Python list range value

Python range() Function: Float, List, For loop Examples

Python range() is a built-in function available with Python from Python(3.x), and it gives a sequence of numbers based on the start and stop index given. In case the start index is not given, the index is considered as 0, and it will increment the value by 1 till the stop index.

For example range(5) will output you values 0,1,2,3,4 .The Python range()is a very useful command and mostly used when you have to iterate using for loop.

Syntax

Parameters

  • start: (optional) The start index is an integer, and if not given, the default value is 0.
  • stop: The stop index decides the value at which the range function has to stop. It is a mandatory input to range function. The last value will be always 1 less than the stop value.
  • step: (optional).The step value is the number by which the next number is range has to be incremented, by default, it is 1.
Читайте также:  Python django create app

Return value

The return value is a sequence of numbers from the given start to stop index.

Python range() Function and history

Python range() has been introduced from python version 3, before that xrange() was the function.

Both range and xrange() are used to produce a sequence of numbers.

Following are the difference between range and xrange():

range() xrange()
The range() gives the sequence of numbers and returns a list of numbers. The xrange() function gives a generator object that needs to be looped in a for-loop to get the values.
The range() returns a list. xrange() returns a generator object.
The range() method uses more memory as the list returned has to be stored in comparison to xrange(). As xrange() returns a generator object, it does not give values instantly and has to be used inside for-loop to get the values.
The usage of memory is more hence the code execution is slow when working on a huge set of data. The code execution is faster using xrange().

Using range()

This example shows how to print the values from 0-9 using range().

The value used in range is 10, so the output is 0 1 2 3 4 5 6 7 8 9

Since the start is not given the start is considered as 0 and the last value is given till 9. The last value is always 1 less than the given value i.e. stop-1.

for i in range(10): print(i, end =" ")

Using start and stop in range()

In the code, the start value is 3, and stop value is 10. Here the start index is 3, so the sequence of numbers will start from 3 till the stop value. The last value in the sequence will be 1 less than the stop value 10-1 = 9.

for i in range(3, 10): print(i, end =" ")

Using start, stop and step

The start value is 3, so the sequence of numbers will start at 3. The stop value is 10, so the sequence of numbers will stop at (10-1) i.e 9. The step is 2, so each value in the sequence will be incremented by 2. If the step value is not given, the value for step defaults to 1.

for i in range(3, 10, 2): print(i, end =" ")

So far, we have seen how range() function gives the incremented value for the stop value given. Let us now try an example to get the decremented value in the range given.

Incrementing the values in range using a positive step.

The parameter step in range() can be used to increment /decrement the values. By default, it is a positive value 1. So it will always give incremented values.

The step value has to be positive incase you want to want incremented values as ouput.

for i in range(1, 30, 5): print(i, end =" ")

Reverse Range: Decrementing the values using negative step

The parameter step with negative value in range() can be used to get decremented values. In the example below the step value is negative so the output will be in decremented from the range value given.

for i in range(15, 5, -1): print(i, end =" ")
15 14 13 12 11 10 9 8 7 6

The start value is 15, the stop value is 5 and the step value is negative number i.e -1. With above inputs range() function will decrement the value from 15 onwards till it reaches the stop value , but here the difference is the last value will be stop + 1.

Using floating numbers in Python range()

Let us now work on the range() using floating-point numbers.

for i in range(10.5): print(i, end =" ")

In above example we have used stop value as 10.5.

Traceback (most recent call last): File "python_range.py", line 1, in for i in range(10.5): TypeError: 'float' object cannot be interpreted as an integer

Python gives an error as the range() function does not support floating-point numbers for start, stop and step.

Using for-loop with Python range()

In this example we will use a array of numbers and, let us see how to use the iterate the array inside for-loop using range()

arr_list = ['Mysql', 'Mongodb', 'PostgreSQL', 'Firebase'] for i in range(len(arr_list)): print(arr_list[i], end =" ")
MysqlMongodb PostgreSQL Firebase

In above example we have used len(arr_list) as the stop value. The for loop will iterate till the stop value i.e the length of the array and that will be 4, as we have four items in the arr_list. The start value will be 0 and step will be 1.So the values will start from 0 and will stop at 3 i.e length of array -1 meaning 4 -1 = 3.

Using Python range() as a list

In this example will see how to make use of the output from range as a list.

You can see the output is a list format. It was not necessary to loop the range() and using list() method we could directly convert the output from range to list format.

Using characters in python range()

So far, we have used integers in python range(). We have also seen that floating-point numbers are not supported in python range. Let us try and see the output as to what happens when we use characters.

for c in range ('z'): print(c, end =" ")
Traceback (most recent call last): File "python_range.py", line 1, in for c in range ('z'): TypeError: 'str' object cannot be interpreted as an integer

It throws an error saying a string cannot be interpreted as an integer.

To get the list of the alphabets you can customize the code and get the desired outputas shown below:

def get_alphabets(startletter, stopletter, step): for c in range(ord(startletter.lower()), ord(stopletter.lower()), step): yield chr(c) print(list(get_alphabets("a", "h", 1)))

How to Access Range Elements

You can make use of a for-loop to get the values from the range or use the index to access the elements from range().

Using for-loop

Using index

The index is used with range to get the value available at that position. If the range value is 5, to get the startvalue, you can use range(5)[0] and the next value range(5)[1] and so on.

startvalue = range(5)[0] print("The first element in range is = ", startvalue) secondvalue = range(5)[1] print("The second element in range is = ", secondvalue) lastvalue = range(5)[-1] print("The first element in range is codepython">print(list(range(10)))

It gives the list output for the range given.

Example: Get even numbers using range()

Using range() will get the list of even numbers in the range given as input. The parameters for range() are, start is 2, stop is 20, and step is 2, so the values will be incremented by 2 and will give even numbers till stop-2.

for i in range(2, 20, 2): print(i, end =" ")

Merging two-range() outputs

In this example will concatenate 2 range() functions with the help of itertools module chain() function.

from itertools import chain print("Merging two range into one") frange =chain(range(10), range(10, 20, 1)) for i in frange: print(i, end=" ")
Merging two range into one 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Using range() With NumPy

The NumPy module has arange() function that works and gives similar output like range(). The arrange() takes in the same parameters like range().

To work with NumPy follow the steps given below.

Step 1: Import NumPy module

Incase while execution, it gives an error saying numpy module not found, you need to install the module as shown in step 2.

Step 2: Install NumPy

Step 3: Working Example of arange() using NumPy

import numpy as np for i in np.arange(10): print(i, end =" ")

Floating point numbers using NumPy arange()

It is not possible to get the floating point sequence using range(), but it is possible using NumPy arange().

The range that we want is from 0.5 to 1.5. The value will be increment by 0.2.

import numpy as np for i in np.arange(0.5, 1.5, 0.2): print(i, end =" ")
0.5 0.7 0.8999999999999999 1.0999999999999999 1.2999999999999998

The output we get is a little weird,some of the float numbers are shown with 16 decimal places. This happens because of the complexity of storing decimal floating numbers into binary format. You can also round the values if required and limit them to the decimal places you need.

Summary

  • Python range() is a built-in function available with Python from Python(3.x), and it gives a sequence of numbers based on the start and stop index given. In case the start index is not given, the index is considered as 0, and it will increment the value till the stop index.
  • Python range() has been introduced from python version 3, prior to that xrange() was the function.
  • The range() gives the sequence of numbers and returns a list of numbers. The xrange() function gives a generator object that needs to be looped in a for-loop to get the values.
  • The parameter step in range() can be used to increment /decrement the values. By default, it is a positive value 1. So it will always give incremented values.
  • Python gives an error for floating-point numbers as the range() function supports only integer values.
  • The values from range() can be accessed using for-loop, using index and list()
  • The NumPy module has arange() function that works and gives similar output like range(). The arange() takes in the same parameters as range().
  • It is possible to get the floating-point sequence NumPy arange() that is not supported using range().

Источник

Python — Access List Items

List items are indexed and you can access them by referring to the index number:

Example

Print the second item of the list:

Note: The first item has index 0.

Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the list:

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

Example

Return the third, fourth, and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

Example

This example returns the items from the beginning to, but NOT including, «kiwi»:

By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from «cherry» to the end:

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:

Example

This example returns the items from «orange» (-4) to, but NOT including «mango» (-1):

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if «apple» is present in the list:

thislist = [«apple», «banana», «cherry»]
if «apple» in thislist:
print(«Yes, ‘apple’ is in the fruits list»)

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью