0

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.

1
  • 1
    list(range(n,0,-1))? Commented Aug 13, 2021 at 4:12

3 Answers 3

1

Use range() functions's step parameter

>>> n=4
>>> list(range(n,0,-1))
[4,3,2,1]
Sign up to request clarification or add additional context in comments.

Comments

0

Use range() function. Docs

range(start, end, step)

  • start - Number where you want to start from
  • end - Number where you want to end (not incuding end)
  • step - How much should the numbers be incremented at each 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].

2 Comments

list(range(4,0,-1)). range is a generator
A 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).
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.