I have a number in python
n = 4
what I want is a countdown list like this:
[4,3,2,1]
Do I need to build a custom function or is there some one line magic that can take any number and create a list.
Use range() function. Docs
range(start, end, step)
So in your case it should be
range(4,0,-1)
If you want a list - Then list(range(4,0,-1)) will give you [4,3,2,1].
range object isn't actually a generator, it's a sequence. In many situations it may be just as good to as a list (though sometimes you do need a real list, like if you need to mutate it later).Well I world suggest you to use numpy as it is easier to use but if you want to use a function, you can use it too.
Well if you use numpy then you have to np.arange(). You can use it just by passing one parameter but at that point, the array will start from 0 to the number one less from that is passed. But so f you want to make a function then a for loop will be used in it.
I have added the code for both suggestions down bellow. Both of them give the same result [4,3,2,1]. The [::-1] is to revert the list i.e. from [0,1,2] to [2,1,0].
import numpy as np
print(list(np.arange(1,5))[::-1])
def n (a):
l = []
for i in range(1,a+1):
l.append(i)
return l[::-1]
print(n(4))
list(range(n,0,-1))?