list_1 = ['1','2','3','4','5','6','7','8']
list_2 = ['n1','n2','n3','n4','n5','n6','n7','n8','n9','n10']
list_3 = ['o1','o2','o3','o4','o5','o6','o7','o8','o9','o10']
cols = zip(list_1,list_2,list_3)
with open('file.csv', 'w', newline='') as f:
thewriter = csv.writer(f)
thewriter.writerow(['list_1','list_2','list_3'])
for col in cols:
thewriter.writerow(col)
list1 list2 list3
1 n1 o1
2 n2 o2
3 n3 o3
4 n4 o4
5 n5 o5
6 n6 o6
7 n7 o7
8 n8 o8
list1 list2 list3
1 n1 o1
2 n2 o2
3 n3 o3
4 n4 o4
5 n5 o5
6 n6 o6
7 n7 o7
8 n8 o8
n9 o9
n10 o10
I have 3 lists, list_1
has 8 items, list_2
has 10 items and list_3
also have 10 items,
but when I write the lists to csv, list_2
and list_3
columns do not show the last 2 items.
It's the default behavior of zip
: truncate to the length of the shortest iterable. You can use zip_longest
instead:
from itertools import zip_longest
cols
with:cols = zip_longest(list_1,list_2,list_3, fillvalue="")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With