0

I have this function:

def second(n):
    z =0
    while z  < n:
        z = z +1
        for i in range(n):
            print(z)

which produces this output for second(3):

1
1
1
2
2
2
3
3
3

How can I store these in a list for further use?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
aaaa
  • 265
  • 1
  • 4
  • 9

3 Answers3

1

Print doesn't save the results - it just sends them (one at a time) to standard output (stdout) for display on the screen. To get an in order copy of the results I humbly suggest you turn this into a generator function by using the yield keyword. For example:

>>> def second(n):
...     z =0
...     while z  < n:
...         z = z +1
...         for i in range(n):
...             yield z
... 
>>> print list(second(3))
[1, 1, 1, 2, 2, 2, 3, 3, 3]

In the above code list() expands the generator into a list of results that you can assign to a variable to save. If you want to save a list of all the results for second(3) you could alternatively do results = list(second(3)) instead of printing it.

0

You could utilise itertools here to return an iterable for you, and either loop over that, or explicitly convert to a list, eg:

from itertools import chain, repeat

def mysecond(n):
    return chain.from_iterable(repeat(i, n) for i in xrange(1, n))

print list(mysecond(3))
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

Here is a generator expression example:

list(j+1 for i in xrange(n) for j in [i]*n)
dansalmo
  • 11,506
  • 5
  • 58
  • 53