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 22, 2018 in Python by ana1504.k
• 7,910 points
5,060 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 22, 2018 by SDeb
• 13,300 points

Related Questions In Python

+4 votes
3 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]

Try using this question by list comprehension: a=[4,7,3,2,5,9] print([x for ...READ MORE

answered Dec 9, 2019 in Python by vinaykumar
• 200 points
34,911 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, 2019 in Python by Nisa
• 1,090 points
5,263 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, 2019 in Python by Shubham Bansal
5,690 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
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,300 points
1,002 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, 2019 in Python by SDeb
• 13,300 points
2,230 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP