gliemezis
gliemezis

Reputation: 828

Zip together each element of one list

Start with a list of strings. Each string will have the same number of characters, but that number is not predetermined, nor is the unrelated total number of strings.

Here is an example:

data = ['ABC', 'EFG', 'IJK', 'MNO']

My desired final output is something like:

[('A', 'E', 'I', 'M'), ('B', 'F', 'J', 'N'), ('C', 'G', 'K', 'O')]

My desired output is what I am expecting to see after using zip() in some way. My problem is that I cannot find the right way to zip each element of one array together.

Essentially, I am trying to get the columns out of a group of rows.

What I have tried so far:

  1. Splitting the data into a two dimensional list:

    split_data = [list(row) for row in rows]

which gives me:

[['A', 'B', 'C'], ['E', 'F', 'G'], ['I', 'J', 'K'], ['M', 'N', 'O']]
  1. Trying to use zip() on that with something like:

    zip(split_data)

I continue to end up with this:

[(['A', 'B', 'C'],), (['E', 'F', 'G'],), (['I', 'J', 'K'],), (['M', 'N', 'O'],)]

Obviously, it is zipping each element with nothing, causing it to return the original data tupled with a blank. How can I get zip() to consider each element of data or split_data as a list that should be zipped?

What I need is zip(data[0], data[1], data[2], ...)

Upvotes: 6

Views: 1952

Answers (1)

alecxe
alecxe

Reputation: 473863

Just unpack the data:

>>> data = ['ABC', 'EFG', 'IJK', 'MNO']
>>> zip(*data)
[('A', 'E', 'I', 'M'), ('B', 'F', 'J', 'N'), ('C', 'G', 'K', 'O')]

As for the explanation, I cannot explain it better and more concise than @Martijn did here:

Upvotes: 8

Related Questions