Reputation: 13
this is my code
for i in range(1,5):
print(i for x in range(1,i+1))
for this code the output is
<generator object at 0x0000025B9C7A9BA0>
<generator object at 0x0000025B9C7A9BA0>
<generator object at 0x0000025B9C7A9BA0>
<generator object at 0x0000025B9C7A9BA0>
Upvotes: 1
Views: 78
Reputation: 15456
When you write
i for x in range(1,i+1)
that is a "generator expression" and it results in a "generator" (<generator object at ...>
), which is an "iterable". Lists are also iterables. A generator's advantage is that it only actually evaluates the element expression (here i
) when you iterate over it.
You seem to want an actual list though. You can immediately create a list like so:
[i for x in range(1,i+1)]
Or in your code:
for i in range(1,5):
print([i for x in range(1,i+1)])
The expression [... for ... in ...]
is a "list comprehension". It looks similar to a generator expression, but it creates a list directly, without a generator. List comprehensions came first to Python, then came generator expressions. They have the same syntax inside different braces.
If you have a generator already, you could also turn it into a list:
for i in range(1,5):
gen = (i for x in range(1,i+1))
print(list(gen)) # get all the elements and make a list
That generator is then "used up" and has no more elements to give.
Upvotes: 1
Reputation: 24059
you need create list
.
try this:
for i in range(1,5):
print([i for x in range(1,i+1)])
in short format you can try this:
print([i for i in range(1,5) for x in range(1,i+1)])
or
list(map((lambda x : print([x for _ in range(1,x+1)])), range(1,5)))
or by thanks of @Sujay for run faster you can use tuple
like below:
tuple(map((lambda x : print([x for _ in range(1,x+1)])), range(1,5)))
for check runtime i use below code:
%timeit tuple(map((lambda x : print([x for _ in range(1,x+1)])), range(1,5)))
# 794 µs ± 86.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit list(map((lambda x : print([x for _ in range(1,x+1)])), range(1,5)))
# 806 µs ± 150 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Upvotes: 4