Akrios
Akrios

Reputation: 1977

Convert one-dimensional lists to multi-dimensional lists

For example, I have two lists

a = [1,2,3]
b = [4,5,6]

I want to make a list c which in format of

c = [[1,4],[2,5],[3,6]]

Since I am new to Python, Can anyone help me. Thank you.

Upvotes: 0

Views: 61

Answers (3)

Philip Tzou
Philip Tzou

Reputation: 6438

Use zip (the example code is Python 2 style):

a = [1, 2, 3]
b = [4, 5, 6]
print zip(a, b)
# [(1, 4), (2, 5), (3, 6)]

Python 3 style:

a = [1, 2, 3]
b = [4, 5, 6]
print(list(zip(a, b)))
# [(1, 4), (2, 5), (3, 6)]

Upvotes: 4

Neo
Neo

Reputation: 4478

a = [1,2,3]
b = [4,5,6]
c = zip(a,b)
c = [list(k) for k in c]

Upvotes: 0

Darkstarone
Darkstarone

Reputation: 4730

If you actually want internal lists instead of tuples you can use:

a = [1,2,3]
b = [4,5,6]
c = [list(result) for result in zip(a,b)]
# c = [[1,4],[2,5],[3,6]] 

Upvotes: 1

Related Questions