Convert Range to a List in Python

If you need to create a list from range, you can use the list constructor. This constructor will convert a range into list elements.

my_list = list(range(10))
print(my_list)

If you run the code, you will get 10 elements starting from 0 to 9.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

For Python 2

The above code works both for Python 3 and 2. If you are using Python 2, you can also use this code to get the same result.

new_list = range(10)
print(new_list)

Using the for loop

The method I showed you is the simplest way to do it. If you want, you can also do it using a loop.

my_list = []
for i in range(10):
    my_list.append(i)

print(my_list)

The result is the same as before.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Unpacking argument

For efficiency reasons, Python 3 no longer creates a list when you use the range function.

Python 3 range is similar to xrange from Python 2 โ€“ it creates an iterable range object.

If you want Python 3 to create a list, you can force it, using the positional-expansion operator.

new_list = [range(10)]
old_list = [*range(10)]

print(new_list)
print(old_list)

Now, you have two results. In the first one, the result is not unpacked. In the second one, there is a standard list.

[range(0, 10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]