TheEpicWatermelon
TheEpicWatermelon

Reputation: 11

Adding Numbers to a list using variable

I'm doing a programming question and I need a bit of help. I have a variable where I type in a number and then that number and all the numbers before it go in a list.

For example: I pick 10 and put it in a variable

And all numbers from 1 - 10 are put in a list

Here is my code:

 Top_Num = int(input('Top Number'))
 Nums = []

Now lets say I chose 10 for the Top_Num, how do I put 10 numbers into the list? Thanks.

Upvotes: 0

Views: 263

Answers (2)

flyingjam
flyingjam

Reputation: 56

Nums = [num for num in range(1, Top_Num + 1)]

It uses list comprehensions too, which is (kinda) an important concept in python.

Upvotes: 2

challett
challett

Reputation: 906

You can actually use Pythons built in range(int) function to do exactly this.

If you want the array to start at 1 and include the input number, you can use

Nums = list(range(1, Top_Num + 1))

The first argument of 1 indicates the start value of the array, and the second argument Top_Num + 1 is the number that the array goes up to (exclusive).

Upvotes: 3

Related Questions