Viswa
Viswa

Reputation: 55

Concatenating list with nested list

a = [1, 2]
b = [[5,6], [7,8]]
c = list(zip(a, b))
print("c zipped:", c)
i = 0
lenghta = len(a)
c = []
while i < lengtha:
    temp_list = [a[i], b[i]]
    c.append(temp_list)
    i += 1
print("c: ", c)

output:

c zipped: [(1, [5, 6]), (2, [7, 8])] c:  [[1, [5, 6]], [2, [7, 8]]]

What I am expecting is:

[[1, 5, 6], [2, 7, 8]]

Upvotes: 0

Views: 43

Answers (4)

FraggaMuffin
FraggaMuffin

Reputation: 4225

you can also use itertools.chain

>>> from itertools import chain
>>> a = [1, 2]
>>> b = [[5,6], [7,8]]
>>> c = [list(chain([x], y)) for (x, y) in zip(a, b)]
>>> c
[[1, 5, 6], [2, 7, 8]]

Upvotes: 1

Transhuman
Transhuman

Reputation: 3547

Using zip and list comprehension

a = [1, 2]
b = [[5,6], [7,8]]

[[i]+j for i,j in zip(a,b)]
#[[1, 5, 6], [2, 7, 8]]

Upvotes: 1

user9429054
user9429054

Reputation:

I know this isn't using zip(), but you could do:

c = []
for i in range(len(a)):
    c.append([a[i], b[i]])

Upvotes: 1

Phydeaux
Phydeaux

Reputation: 2855

This seems overcomplicated. Try this, using a list comprehension:

a = [1, 2]
b = [[5,6], [7,8]]

c = [[x] + b[i] for i, x in enumerate(a)]

Upvotes: 1

Related Questions