Search code examples
pythondjangodjango-pagination

Is there a way to convert integer to a list of integers counting upwards?


Just say I have an integer in Python, ex: 100.

I'd like to convert this integer into a list counting up to this integer, ex: [1,2,3,... 100]

What is the most efficient way to do this?

(In case you're wondering why I want to do this, it's because the Django Paginate library I want to use needs a list -- if there's a more elegant way to use Paginate without doing this, please let me know).


Solution

  • The Python range() built-in does exactly what you want. E.g:

    range(1, 101)
    

    Note that range() counts from 0, as is normal in Computer Science, so we need to pass 1, and it counts until the given value, not including - hence 101 here to count to 100. So generically, you want range(1, n+1) to count from 1 to n.

    Also note that in 3.x, this produces an iterator, not a list, so if you need a list, then you can simply wrap list() around your call to range(). That said - most of the time it's possible to use an iterator rather than a list (which has large advantages, as iterators can be computed lazily), in that case, there is no need to make a list (in 2.x, functionality like that of range in 3.x can be achieved with xrange().