Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I have 3 lists of n length that I want to combine into one list, then combine all the nth indexes together in a list, and produce the output with each element in a separate column in a csv file

list_1 = ["john", "peter", "steve", "mike", "paul"] 

list_2 = ["green", "red", "blue", "purple", "orange"] 

list_3 = [["dog", "cat"], "rabbit", "dog", "", ["cat", "mouse", "elephant"]

What should i do:

1 Answer

0 votes
by (25.1k points)

Easiest way to do it is to check if the last item is a list using the isinstance method, if so then extend it else use it as it:

list_1 = ["john", "peter", "steve", "mike", "paul"]

list_2 = ["green", "red", "blue", "purple", "orange"]

list_3 = [["dog", "cat"], "rabbit", "dog", "", ["cat", "mouse", "elephant"]]

 

combined_list = list(map(list, zip(list_1, list_2, list_3)))

for items in combined_list:

    if isinstance(items[-1], list):          #Check if last element is list.

        writer.writerow(items[:-1] + items[-1])

    else:

    writer.writerow(items)

Browse Categories

...