How to print the output of a generator [duplicate] - python

This question already has answers here:
How to print a generator expression?
(8 answers)
Closed 7 years ago.
When I run the code I get the following output
How do I print the print the output?
def firstn(n):
num=0
while num < n:
yield num
num=num+1
sum_of_first_n=sum(firstn(10))
print(firstn(3))

In general:
print(list(firstn(n)))
Be sure your generator is not infinite. If you are not sure, use something like:
import itertools as it
print(list(it.islice(firstn(n), 100)))
to print up to the first 100 elements.

There's different ways of doing that, but basically you have to iterate through the iterator. The simplest way is probably using list comprehension:
print(list(firstn(3)))
but if you wish you could write a for loop to do that (and get it fx one element per line):
for e in firstn(3):
print(e)
One should however be aware that iterating through the generator consumes it and if you don't have means of retrieving a new generator (for example if you got the generator as parameter to a function call) you would have to store the values - fx in an array:
l = list(firstn(3))
for e in l:
print(e)
for e in l:
do_something(e)

Related

did I did something wrong with list and for loop in python? [duplicate]

This question already has answers here:
Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?
(9 answers)
Closed 1 year ago.
the thing that I am supposed to do is,
get 10 int
find the different value after doing %42 for those 10 input int
and what I thought is, like this
n = []
for i in range(10):
a = int(input())
n[i] = a%42
s = set(n)
print(len(s))
but it didn't work with a message of
----> 4 n[i] = a%42
IndexError: list assignment index out of range
and by googling I have solved this question by adding append.
n = []
for i in range(10):
a = int(input())
print("a",a)
b = a%42
print("b",b)
n.append(b)
s = set(n)
print(len(s))
** here is my question. why did my code didn't work? I thought my method's logic is solid. Is there some knowledge that I am missing about? **
thank you previously.
actually when you were trying first way you were using lists built-in dunder(magic method) which asks that there must be an element at that index before changing its value, meanwhile list is empty and hence it can't find an element whose value has to be chanced but append works something like this:
yourList += [newElement]
which is basically like list concatination.
Your code doesn't work because n is an empty list so it has no sense to assign a value to an index.
If you know the size of your list you can do:
# this works
n = [size]
n[0] = 1

Function that appends to list of choice [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 4 years ago.
I'm trying to create a function with two inputs that can append a value into a list of choice. I'm starting of with two lists to get the code working before I build up.
a = []
b = []
def func(z,x):
if z == a:
a.append(x)
elif z == b:
b.append(x)
print(a,b)
For some reason it appends to the first list, then the second, no matter which I select. I've only just started to learn python, so I may have missed something basic.
== when comparing two lists sees if they contain the same items. An empty list is equivalent to another empty list, so the first time that function is called, it will always append to a. What you could use instead is is (if z is a:), but a much better way is to ignore a and b, and just use z directly:
def func(z, x):
z.append(x)
print(a, b)
which brings up doubts as to why this function is needed...

How do I make an infinite for loop in Python (without using a while loop)? [duplicate]

This question already has answers here:
Looping from 1 to infinity in Python
(8 answers)
Closed 6 years ago.
Is there way to write an infinite for loop in Python?
for t in range(0,10):
if(t == 9): t= 0 # will this set t to 0 and launch infinite loop? No!
print(t)
Generally speaking, is there way to write infinite pythonic for loop like in java without using a while loop?
The itertools.repeat function will return an object endlessly, so you could loop over that:
import itertools
for x in itertools.repeat(1):
pass
To iterate over an iterable over and over again, you would use itertools.cycle:
from itertools import cycle
for t in cycle(range(0, 4)):
print(t)
This will print the following output:
0
1
2
3
0
1
2
3
0
1
...
You should create your own infinite generator with cycle
from itertools import cycle
gen = cycle([0])
for elt in gen:
# do stuff
or basically use itertools.count():
for elt in itertools.count():
# do stuff
Just pass could help with forever true value.
while True:
pass

When iterating through a list in python, how can I get the current number of "i"? [duplicate]

This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 8 years ago.
I have a list and am iteratively performing a function on each item. I am trying to print out how far through the iteration the script is. The problem is that I can't easily get the position.
Here is what I have so far, but it generates a ValueError: 'item' is not in list.:
that_number = len(mylist)
for i in mylist:
this_number = mylist.index(i)
print this_number, " out of ", that_number
DO SOMETHING
print "Done!"
I am aiming for the output:
1 out of 3
2 out of 3
3 out of 3
Done!
This question is related in that it is trying to find the position in a list, however is there a valid way of getting the element position without using enumerate?
the enumerate() function really gives you what you want. For other ways to do it though, you can do a for loop over a range:
for i in range(len(myList)):
print myList[i], "at index", i
range(len(myList)) creates a list from 0 to len(myList) - 1 so you can use that to index into each element of the list.
Use a Generator Instead
For long lists creating another list the size of your original to loop over may be undesirable. Here is the same code as above for both python2 and 3 which will execute a for loop over a generator instead of a list.
Python 2
For Python 2, just use xrange instead of range:
for i in xrange(len(myList)):
print myList[i], "at index", i
Python 3
For Python 3 range returns a generator, so lets just change the print statement:
for i in range(len(myList)):
print(myList[i], "at index", i)
mmm, you'll have issue with duplicates on your list. If it's only for debugging/display purposes
that_number = len(mylist)
this_number=0
for i in mylist:
this_number+=1
print this_number, " out of ", that_number
DO SOMETHING
print "Done!"
how would you deal with a list containing [1,2,3,2,1] ?

Don't go to next iteration in for loop [duplicate]

This question already has answers here:
repeat an iteration of for loop
(4 answers)
Closed 8 years ago.
Not sure if this is possible, mostly a curiosity question although I may have a case where this may be useful. Basically I'm wondering if it's possible to not go to the next iteration in a loop, and instead try repeating that iteration. For example:
myList = ['a','b','c']
for thing in myList:
if something:
continue
else:
try again (same iteration)
Is what I'm asking for clear? A way I've seen of doing this is to use a while loop operating only on the first element of a list and then continuously deleting the first element of the list if some condition is met.
Thanks
You can use a while loop and manually substract from the iteration variable. Demo:
import time
myList = [1,2,3,4,5,6,7,8]
i = 0
while i < len(myList):
time.sleep(1)
print(i)
if i == 3:
i -= 1
i += 1
Of course, you'll need to access your thing by indexing into myList now, i.e. do something to/with myList[i].

Categories