-1

Suppose I have a list of numbers divided into 3 lists:

numbers = [[0,1,2], [3,4,5], [6,7,8]]

And I want to iterate through each 3 lists and divide them into columns:

0  1  2
3  4  5
6  7  8

How would I go about doing this? So far, I can only print out 1 column:

for column in numbers[0:3]:
    column1 = column[0]
    print( column1 )
Julien
  • 13,986
  • 5
  • 29
  • 53
Amina
  • 11
  • Uh what do you mean "columns" exactly? – SuperStew Nov 15 '17 at 05:26
  • I meant by instead of printing each list in numbers (which is like a row), but printing the first numbers in each list and then printing the 2nd numbers and etc. Kind of like counting down. – Amina Nov 15 '17 at 05:29

4 Answers4

1

You should use two loops, one for the rows, the other for the columns. In Python 3 it looks like this:

for i in range(3):
    for j in range(3):
        print(numbers[i][j], end=' ') # print a single value in same line
    print()                           # print line break after each row
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • @Amina glad to be of help :) I this answer was useful for you, please don't forget to [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it, simply click on the check mark to its left – Óscar López Nov 15 '17 at 12:48
0

You can just use your code and add

column1 = column[0,:]

result: [0,1,2] or

column1 = column[:,0]

result: [0,3,6]

Max Krappmann
  • 490
  • 5
  • 19
0

I think you can try the following:

for n in numbers:
    for i in n:
        print(i, end=" ")
    print()

The 1st loop goes through your list and the 2nd loop goes through each element in the sub lists. With "end" you specify what you want to print after each element. By default, it’s a new line. And by using print() after going through 2nd loop you print elements from sub lists on separate lines. Hopefully my explanation is clear enough.

Vlad
  • 1
  • 1
  • 2
0

This works for me in python 2.7

i=0
for column in numbers[0:3]:
     print column[i],column[i+1],column[i+2]