Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 range() Function Usage

Python3 range() Function Usage

Python3 Built-in Functions Python3 built-in function

The Python3 range() function returns an iterable object (of type object), not a list, so printing it does not print a list.

The Python3 list() function is an object iterator that can convert the iterable returned by range() into a list; the resulting variable is of list type.

Python2 The range() functionreturns a list.

Function syntax


range(stop)
range(start, stop[, step])

Parameter Description:

Example

If only the start and end values are given, the step defaults to 1:

Example

for

number

in

range

(

1

,

6

)

:

   

print

(

number

)

The output is:

1
2
3
4
5

If only one argument is given, it generates a sequence of integers starting from 0; that argument is the end value and the step defaults to 1:

Example

for

number

in

range

(

6

)

:

   

print

(

number

)

The output is:


0
1
2
3
4
5

You can specify a step so that the value increases by a different amount each time:

Example

for

number

in

range

(

1

,

6

,

2

)

:

   

print

(

number

)

The output is:

1
3
5

Note: The end value 6 is not included.

In addition, we can use a negative step to generate the sequence in reverse order from the end value:

Example

for

number

in

range

(

6

,

1

,

1

)

:

   

print

(

number

)

The output is:

6
5
4
3
2

**Note:** If a negative step is used, the start value must be greater than the end value.

If you only need to generate a sequence of integers and do not need to iterate over it with a for loop, you can convert the value returned by range() into a list or tuple, for example:

The following generates a list of integers:

Example

numbers

=

list

(

range

(

1

,

6

)

)

numbers

[

1

,

2

,

3

,

4

,

5

]

The following generates a tuple of integers:

Example

numbers

=

tuple

(

range

(

1

,

6

)

)

numbers

(

1

,

2

,

3

,

4

,

5

)

Python3 Built-in Functions Python3 built-in function