Kodeclik Blog
How to convert a Python range to a list
Remember that a range is a sequence of numbers like from 1 to 10. You typically use the range() function to construct a range, e.g., for use in a for loop.
For instance you typically write a for loop like:
myrange = range(1,11)
for i in myrange:
print(i)
The output will be:
1
2
3
4
5
6
7
8
9
10
(Note that the range starts from 1 and goes till 10, one less than 11, the second index of the range() function.)
You will find a need sometimes to convert a range to a list, i.e., instead of using it in a for loop you might want just a list. Let us try printing the range as is after constructing it:
myrange = range(1,11)
print(myrange)
The output is:
range(1, 11)
which is just printing the range object, not quite a list. Let us learn how to convert a range to a list.
Method 1: Use the list() function
The easiest way to convert a range to a list is to use the list() function. Here is how that works:
myrange = range(1,11)
print(list(myrange))
The output is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Method 2: Use the unpacking operator (*)
The second approach is to use the unpacking operator (*) which unpacks the range that we then enclose in square brackets to generate a list:
myrange = range(1,11)
print([*myrange])
The output is as before:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Method 3: Construct a list and use the extend() method
A third approach first requires you to create a list and then use the extend() method on the list (to which you can pass the range):
myrange = range(1,11)
mylist = []
mylist.extend(myrange)
print(mylist)
The output is again:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You have learnt three different ways to convert a Python range to a list. Which one is your favorite? For more on ranges, checkout our blogpost on reversing a range in Python.
For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.