w3resource

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.

Python: Print a nested lists 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:

Flowchart: Print a nested lists using the print() function

For more Practice: Solve these Related Problems:

  • Write a Python program to print each list element of a nested list recursively.
  • Write a Python program to flatten a nested list while maintaining the original list structure.
  • Write a Python program to print a nested list with indentation based on its depth.
  • Write a Python program to iterate over a nested list and print only non-empty sublists.

Go to:


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.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.