0

I have two lists:

A = ['Apple', 'Dog']
B = ['Cat', 'OWL', 'PEACOCK']

I want output to a csv as :

A

Apple
Dog

B

Cat
OWL
PEACOCK

How can I output these two lists to a csv. I tried with zip but it's only meant for same sized lists

0

1 Answer 1

0

You can add a blank item to list A, and then export it using pandas. Pandas uses a data structure called a DataFrame, but the columns must be equal length. The output .csv file will not show the blank data cell.

import pandas as pd
A = ['Apple', 'Dog']
B = ['Cat', 'OWL', 'PEACOCK']
df1 = pd.DataFrame({'A':A})
df2 = pd.DataFrame({'B':B})
pd.concat([df1,df2],axis=1).to_csv('myfile.csv', index = False)
Sign up to request clarification or add additional context in comments.

4 Comments

That's not a good solution when I will be dealing with multiple lists
Sure it is. You just have to expand it for your use case. Don't expect StackOverflow to do all the work for you. You can also look at the packages xlsxwriter and csv, but pandas is much more versatile for csv/dataframe manipulation.
It's not an optimized way to check the length of each list when I have hundreds of lists and append blank items for each. Thanks for your suggestion though.
import pandas as pd A = ['Apple', 'Dog'] B = ['Cat', 'OWL', 'PEACOCK'] df1 = pd.DataFrame({'A':A}) df2 = pd.DataFrame({'B':B}) pd.concat([df1,df2],axis=1).to_csv('myfile.csv', index = False)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.