A fairly direct way of creating a list as shown is via
[i for i in range(1,n+1) for j in range(i)]
where n
is the largest number to appear in the list. The above is equivalent to the methods used in several previously suggested answers, but slightly cleaner in expression.
An alternative to all the methods mentioned so far is to note that the i
th element of the list is approximately equal to the integer part of the square root of 2*i
. With slight adjustments, this makes a fairly simple generator possible, as follows.
def gen_nnlist(nmax):
n = 1
while n < nmax*(nmax+1):
yield int(n**.5+.5)
n += 2
Here is some sample output from exercising the code in the 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
>>>
f(2) -> [1, 2, 2]
? – Useless Nov 5 '12 at 16:28