sgzhan
sgzhan

Reputation: 51

Unpack a nested list

My question is simple. There are two lists. The first is a list of integers:

a = [1, 2, 3]

The other is a list of lists:

b = [['a', 'b'], ['c', 'd'], ['e', 'f']]

How could I get the result below:

result = [[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]

Thanks.

Upvotes: 3

Views: 1900

Answers (5)

JoshMock
JoshMock

Reputation: 1301

Using Python's enumerate function you can loop over a list with an index. Using x.extend(y) will prepend the values in list x to list y.

a = [1, 2, 3]
b = [['a', 'b'], ['c', 'd'], ['e', 'f']]

result = []
for index, value in enumerate(a):
    aa = [value]
    aa.extend(b[index])
    result.append(aa)

Upvotes: 0

xuxu
xuxu

Reputation: 1

The following Python code will unpack each list and assemble it in the form you indicated.

[[a[i]] + b[i]  for i in range(min(len(a),len(b)))]

Upvotes: 0

eumiro
eumiro

Reputation: 213125

>>> a = [1, 2, 3]
>>> b = [['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> [[aa] + bb for aa, bb in zip(a, b)]
[[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]

Upvotes: 10

Nick
Nick

Reputation: 354

Another way to do this would be:

index = 0
l = b
for i in a:
    l[index].append(i)
    index += 1

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304503

In Python3

>>> a = [1, 2, 3]
>>> b = [['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> [aa+bb for *aa, bb in zip(a,b)]
[[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]

Upvotes: 3

Related Questions