list1 = [[],[],[]]
list2 = [[1,2,3],[4,5,6],[7,8,9]]
i = 0
j = 0
k = 0
while i < len(list1):
    list1[i].append(list2[j][k])
    i += 1
    k += 1

I want my output for list1 to be [[1,4,7],[2,5,8],[3,6,9]]. The problem is I don't know how to advance through the lists in list2. Can you help me out?

list1 = [[],[],[]]
list2 = [[1,2,3],[4,5,6],[7,8,9]]
i = 0
j = 0
k = 0
while i < len(list1):
    list1[i].append(list2[j][k])
    i += 1
    k += 1

I want my output for list1 to be [[1,4,7],[2,5,8],[3,6,9]]. The problem is I don't know how to advance through the lists in list2. Can you help me out?

why can't you do list1 = list2 EDIT: i just realized that's not your purpose
hold on, i'm thinking of a solution

EDIT2:here's the solution
python 3.0 code

list1 = [[],[],[]]
list2 = [[1,2,3],[4,5,6],[7,8,9]]
i = 0
while i < len(list1):
    list1[i] = [l[i] for l in list2]
    i+=1
print(list1)

Thanks for the reply, but I absolutely cannot understand Python 3.0 code. Can you write it as it is written for earlier versions?

print(list1)
to
print list1

and that's it.

so it becomes

list1 = [[],[],[]]
list2 = [[1,2,3],[4,5,6],[7,8,9]]
i = 0
while i < len(list1):
    list1[i] = [l[i] for l in list2]
    i += 1
print list1

For a one-line solution,

list1=[[l[i] for l in list2] for i in range(len(list2[0]))]

This is basically a comprehension of list comprehensions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.