2

I am learning Python Loops. In code below, I am not able to get desired output.

I want to separate two nested-list values into two seperate lines Code:

list_of_list = [[1,2,3],[4,5,6]]
    for list1 in list_of_list:
        print (list1)
        for x in list1:
            print (x)

Desired Output:

[1, 2, 3]
[4, 5, 6]

My Current output:

1
2
3
4
5
6

Please give advice on how to achieve the desired result.

3
  • 4
    you don't need the second print Commented Oct 15, 2018 at 3:39
  • 4
    Or the second loop, in fact. Commented Oct 15, 2018 at 3:40
  • 1
    for x in list1: print (x) is not needed.. Commented Oct 15, 2018 at 3:40

3 Answers 3

2

Several ways:

1. join

Do:

print('\n'.join([str(i) for i in list_of_list]))

2. list comprehension

Do:

[print(i) for i in list_of_list]

3. for-loop

Do:

for i in list_of_list:
    print(i)

All Output:

This:

[1, 2, 3]
[4, 5, 6]

As desired

To explain why yours is not working:

  • Because too many loops, just need one loop

  • The outer loop is enough for getting desired, you have nested loops so first loop (is what i mean by outer loop)

Sign up to request clarification or add additional context in comments.

Comments

1
list_of_list = [[1, 2, 3], [4, 5, 6]]
for list1 in list_of_list:
    print (list1) #This print gives the desired output & as mentioned in the comment the second print isn't required

Comments

1

you can do this in 1 line:

[print(l) for l in list_of_list]

which translate to:

for l in list_of_list:
    print(l)

Which is what you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.