What is the method for printing nested lists in Python?
There are various ways to output nested lists in Python, depending on the format and requirements. Here are some common methods:
- Using a loop:
- Iterate through each element in the list using nested for loops, and print each element using the print statement.
- Example code: nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for sublist in nested_list:
for item in sublist:
print(item, end=’ ‘)
print() - Use list comprehension:
- Use nested list comprehension to flatten a nested list and print it out using the print statement.
- Example code:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list) - Utilize recursion:
- Write a recursive function to traverse a nested list and print out each element.
- Example code:
def print_nested_list(nested_list):
for item in nested_list:
if type(item) is list:
print_nested_list(item)
else:
print(item)nested_list = [[1, 2, 3], [4, [5, 6]], [7, 8, 9]]
print_nested_list(nested_list)
These methods can be chosen based on specific needs.