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
• 7,870 points
54 views

1 answer to this question.

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
• 13,160 points

Related Questions In Python

0 votes
2 answers

Write a for loop that prints all elements of a list and their position in the list. a = [4,7,3,2,5,9]

a = [4,7,3,2,5,9] b = enumerate(a) for i in ...READ MORE

answered Jul 15 in Python by Kei Tee

edited Jul 22 by Kalgi 193 views
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
• 1,090 points
15 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
33 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,720 points
61 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 216 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
• 13,160 points
50 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
• 13,160 points
25 views