Python: Print a nested lists using the print() function
Python List: Exercise - 48 with Solution
Write a Python program to print nested lists (each list on a new line) using the print() function.
Sample Solution:
Python Code:
# Define a list 'colors' containing sublists, each with a single color name
colors = [['Red'], ['Green'], ['Black']]
# Use a list comprehension to create a new list, where each sublist is converted to a string
# The resulting list contains string representations of the sublists
# The 'join' method is used to concatenate the strings with newline characters '\n' in between
# This creates a multi-line string where each sublist is on a new line
# Print the resulting multi-line string
print('\n'.join([str(lst) for lst in colors]))
Sample Output:
['Red'] ['Green'] ['Black']
Flowchart:
Python Code Editor:
Previous: Write a Python program to insert an element before each element of a list.
Next: Write a Python program to convert list to list of dictionaries.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-48.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics