Python for loop with two variables in func | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python for loop with two variables in func

assume this program: for a,b in thisFunc(): #some code - it doesnt matter if thisFunc() has any parameters or not Now assume that thisFunc produces two values, one goes into a and other into b, but values produced for b are less than those of a. so my question is will the for loop work perfectly fine? arnt there supposed to be errors or is there not supposed to be the use of enumerate() function required?

5th Oct 2020, 5:20 PM
mohsin khan
mohsin khan - avatar
3 Answers
+ 3
This works fine as values in [2,1] is assigned to i,j a=[[2,1],[4,3]] for i,j in a: print(i,j) but a=[1,2,3,4] will obviously give an error if you try to do the above, for that you need to use enumerate for i,j in enumerate(a): print(i,j)
5th Oct 2020, 5:33 PM
Abhay
Abhay - avatar
+ 1
You can definitely do something like this as well! def pack(*args): j=0 while j<len(args): b=args[j],args[j+1] j+=2 yield b for a,b in pack(2,1,4,3,6,5): print(a,b)
5th Oct 2020, 5:53 PM
Abhay
Abhay - avatar
+ 1
@Abhay thanks i will look into it again, right now im very sleepy my brain isnt working anymore, hopefully tomorrow ill tell you more about this, thank you again friend.
5th Oct 2020, 6:12 PM
mohsin khan
mohsin khan - avatar