nestedlists_looping | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

nestedlists_looping

Hi geeks , this community is awesome would like to thank you all for this service and looking for you advise on the below code snippet ,and if there is better way to get the same result. With Many Thanks x =[['a','b','c'],[10,20,30,40,50]] lists=0 for b in range(len(x[-1])): for a in range(len(x[lists])): print(x[lists][a],x[-1][b])

3rd Mar 2017, 11:54 AM
Muhamed Ziedan
Muhamed Ziedan - avatar
1 Answer
+ 2
""" You can get in in once line, using reduce(), lamda and comprehensive list... Anyway, you need to add another line for import the reduce() function ^^ And it's less readable than nested loop: it's not necessarly a good idea, mostly more than it just do implicitly what you are doing explicitly but you can if you really need to shorter you code ;) """ from functools import reduce x =[['a','b','c'],[10,20,30,40,50]] lists = 0 # use of this variable index as you do, but is it necessary? # to get exactly the same result as yours: print('\n'.join(reduce(lambda a,b: a + [ i+' '+str(b) for i in x[lists] if True ],x[-1],[]))) # to get a list of tuples instead: print(reduce(lambda a,b: a + [ (i,b) for i in x[lists] if True ],x[-1],[]))
4th Mar 2017, 9:15 AM
visph
visph - avatar