How to Create a List from 0 to n in Python?

Estimated read time 1 min read

To create a list from 0 to n in Python, you can use the range() function and convert the result to a list using the list() function. Here’s an example:

n = 10  # replace 10 with any desired number
my_list = list(range(n+1))

In this example, we set n to 10 (but you can replace it with any desired number). We use the range() function to generate a sequence of numbers from 0 to n (inclusive). We then convert the resulting sequence to a list using the list() function.

Finally, we print the contents of the list using the print() function.

The resulting output will be:

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

Note that the range() function generates a sequence of numbers that starts at 0 by default. If you want to start at a different number, you can specify the starting value as the first argument to the range() function (e.g., range(1, n+1) to start at 1 and include n in the sequence).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply