Convert Range into a List
Convert Range into a List
To convert a given range object into a List in Python, call list() builtin function and pass the given range object as argument. list() function returns a new list with the values from the range object.
The syntax to convert given range object myrange
into a list mylist
is
mylist = list(myrange)
Example
1. Convert range(start, stop) into a list
In the following example, we take a range object starting at 4, and progressing upto 10 (excluding 10), and convert this range object into a list.
Python Program
# Take a range
myrange = range(4, 10)
# Convert range object into a list
mylist = list(myrange)
print(mylist)
Output
[4, 5, 6, 7, 8, 9]
2. Convert range(start, stop, step) into a list
In the following example, we take a range object with start=4, stop=15, and step=2. And convert this range object into a list.
Python Program
# Take a range
myrange = range(4, 15, 2)
# Convert range object into a list
mylist = list(myrange)
print(mylist)
Output
[4, 6, 8, 10, 12, 14]
Summary
In this tutorial of Python Ranges, we learned how to convert a range object into a list using list() builtin function.