Christoph
Christoph

Reputation: 101

Unzip a list of tuples with variable number of elements

I want to unzip a list of tuples, zipped, of the following form:

zipped1 = [(a, b, c), (d, e, f), (g, h, i)]

using

x, y, z = zip(*zipped1)

However, the number of elements in each tuple is variable; the list can as well look like this:

zipped2 = [(a, b, c, d), (e, f, g, h)]

How can I unzip these two list of tuples with the same command?

Upvotes: 1

Views: 824

Answers (1)

user2390182
user2390182

Reputation: 73460

That's what iterables are for. If you do not know in advance how many objects (of any kind) you expect, do not work with individually named variables, but put them all in a list, tuple or generator:

z = ['abcd', 'efgh']
transposed = list(zip(*z))
# [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', 'h')]

Now you can iterate and process whatever number of tuples there are in the transposed matrix.

Upvotes: 2

Related Questions