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 Answers 3
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)
Comments
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
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
Explore related questions
See similar questions with these tags.
for x in list1: print (x)is not needed..