Return a list inside a for loop while iterating over the elements of another list

0 votes

When I run the following code:

for elems1 in L1:
   ---some-actions---
   for val in value:
      result = val1,val2,val3
      L2.append(result)
      print(L2)

   #additional tasks 
   for vals in L2:
        ---additional-tasks to be performed---

And print (L2) I get the output as :

['val1']
['val1','val2'] 
['val1','val2','val3'] 

I need to iterate over the values of these two lists in nested for loops but it is printing thrice and separating each value. why?

Sep 21, 2018 in Python by ana1504.k
• 6,670 points
30 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

The print() is getting called multiple times as it is inside the loop. Put it outside the loop as such :

for val in value:
      result = val1,val2,val3
      L2.append(result)
print(L2)
answered Sep 21, 2018 by SDeb
• 10,780 points

Related Questions In Python

0 votes
1 answer

How to count the number of elements in a list?

To count the number of elements of ...READ MORE

answered May 27 in Python by Nisa
• 640 points
6 views
0 votes
1 answer

How can I change the iteration variable inside a for loop in python?

Assume you have a list of lists: my_list ...READ MORE

answered Jun 10 in Python by Shubham Bansal
16 views
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,710 points
31 views
+1 vote
4 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
96 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
55 views
0 votes
1 answer

Iterating over dictionaries using 'for' loops

key is just a variable name. for key ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 10,780 points
32 views
0 votes
1 answer

Shorter way to write a Python for loop

You can use the enumerate iterator: for i, ...READ MORE

answered Jan 17 in Python by SDeb
• 10,780 points
17 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.