0
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]]

4 Answers 4

1

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)]
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

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]]

1 Comment

I had a work around using flattening of lists for each row. But I felt that is lot of code. The answers provided by many of you are simple and Pythonic. Feel better now. Thanks
1

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.