About
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.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
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.
The easiest way to convert a range to a list is to use the list() function. Here is how that works:
The output is:
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:
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.
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.
myrange = range(1,11)
for i in myrange:
print(i)
1
2
3
4
5
6
7
8
9
10
myrange = range(1,11)
print(myrange)
range(1, 11)
myrange = range(1,11)
print(list(myrange))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myrange = range(1,11)
print([*myrange])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myrange = range(1,11)
mylist = []
mylist.extend(myrange)
print(mylist)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]