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:
The output will be:
(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:
The output is:
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:
The output is:
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:
The output is as before:
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):
The output is again:
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.
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!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.