nsa
nsa

Reputation: 565

How to print each element of a list of lists of variable length as a column in python?

Consider the following list:

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

How can I achieve this printing pattern?

1 4 7
2 5 8
3 6 9

More specifically, how can I do it in general for any number of elements in L while assuming that all the nested lists in L have the same length?

Upvotes: 0

Views: 70

Answers (2)

user2415706
user2415706

Reputation: 982

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    
for i in zip(*L):        
    print(*i)

Produces:

1 4 7
2 5 8
3 6 9

(*i) says to do all of the arguments inside of i, however many there are.

Upvotes: -1

deadshot
deadshot

Reputation: 9071

Try this:

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for x in zip(*L):
    print(*x)

Output:

1 4 7
2 5 8
3 6 9

Upvotes: 3

Related Questions