A fairly direct way to create a list, as shown, through
[i for i in range(1,n+1) for j in range(i)]
where n is the largest number that should appear in the list. The above is equivalent to the methods used in several of the previously proposed answers, but a little cleaner in expression.
An alternative to all the methods mentioned above is to note that the ith element of the list is approximately equal to the integer part of the square root of 2*i . With minor adjustments, this makes a fairly simple generator possible, as shown below.
def gen_nnlist(nmax): n = 1 while n < nmax*(nmax+1): yield int(n**.5+.5) n += 2
Here is an example of output from code implementation in a python 2.7.3 interpreter:
>>> print [i for i in gen_nnlist(4)] [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] >>> print [i for i in gen_nnlist(6)] [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6] >>> fun = gen_nnlist(3) >>> for i in fun: print i ... 1 2 2 3 3 3 >>>