Python: Print a nested lists using the print() function
Print Nested Lists
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics