Friday, September 5, 2025
HomeLanguagesrange() to a list in Python

range() to a list in Python

Often times we want to create a list containing a continuous value like, in a range of 100-200. Let’s discuss how to create a list using the range() function.

Will this work ?




# Create a list in a range of 10-20
My_list = [range(10, 20, 1)]
  
# Print the list
print(My_list)


Output :

As we can see in the output, the result is not exactly what we were expecting because Python does not unpack the result of the range() function.

Code #1: We can use argument-unpacking operator i.e. *.




# Create a list in a range of 10-20
My_list = [*range(10, 21, 1)]
  
# Print the list
print(My_list)


Output :

As we can see in the output, the argument-unpacking operator has successfully unpacked the result of the range function.
 
Code #2 : We can use the extend() function to unpack the result of range function.




# Create an empty list
My_list = []
  
# Value to begin and end with
start, end = 10, 20
  
# Check if start value is smaller than end value
if start < end:
    # unpack the result
    My_list.extend(range(start, end))
    # Append the last value
    My_list.append(end)
  
# Print the list
print(My_list)


Output :

RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS