Victor
Victor

Reputation: 43

How to export all values of lists to csv on Python

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)

Output

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

Expected Output

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.

Upvotes: 4

Views: 118

Answers (2)

RMPR
RMPR

Reputation: 3531

It's the default behavior of zip: truncate to the length of the shortest iterable. You can use zip_longest instead:

  • Import it first:
from itertools import zip_longest
  • Then replace the line where you assign cols with:
cols = zip_longest(list_1,list_2,list_3, fillvalue="")

Upvotes: 5

Elbert Villarreal
Elbert Villarreal

Reputation: 1716

You can see this Link and this other link

Passing Arguments of Unequal Length When you’re working with the Python zip() function, it’s important to pay attention to the length of your iterables. It’s possible that the iterables you pass in as arguments aren’t the same length.

In these cases, the number of elements that zip() puts out will be equal to the length of the shortest iterable. The remaining elements in any longer iterables will be totally ignored by zip()

In your case, you will get int cuted to the 8th value (the sortest list).

EDIT

You can use this info itertools.zip_longest

itertools.zip_longest(*iterables[, fillvalue])

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Equivalent to:

def zip_longest(*args, fillvalue=None):
     # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
     def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
         yield counter()         # yields the fillvalue, or raises IndexError
     fillers = repeat(fillvalue)
     iters = [chain(it, sentinel(), fillers) for it in args]
     try:
         for tup in zip(*iters):
            yield tup
     except IndexError:
         pass

If one of the iterables is potentially infinite, then the zip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile()). If not specified, fillvalue defaults to None.

Example:

from itertools import zip_longest

l_1 = [1, 2, 3]
l_2 = [1, 2]

combinated = list(zip_longest(l_1, l_2, fillvalue="_"))

print(combinated)  # [(1, 1), (2, 2), (3, '_')]

Upvotes: 3

Related Questions