Reputation: 11
I am trying to understand how to print the following table of numbers to get the desired output:
tableData = [
['1','2','3','4'],
['11','12','13','14'],
['21','22','23','24']
]
The output:
1 11 21
2 12 22
3 13 23
4 14 24
After digging around a bit, I was able to write this following code that gives me the correct answer:
for row in range(len(tableData[0])):
for item in range(len(tableData)):
print(tableData[item][row], end = " ")
print('')
However, I do not understand one thing. In the first line of code, why is the [0] needed? When I remove it the code does not print out the last line 4, 14, 24, and I do not understand why. If someone can explain the logic of adding [0] here I would appreciate it a lot.
Upvotes: 1
Views: 1217
Reputation: 92461
I added this as a comment, but thought a little code might help make the point. This is a great example of making sure variables are well-named in order to make code more readable. This is the same basic code but with variables named to make them self-describing. The original question is answered by the naming:
tableData = [
['1','2','3','4'],
['11','12','13','14'],
['21','22','23','24']
]
num_of_columns = len(tableData[0])
for col in range(num_of_columns):
for row in tableData:
print(row[col], end = " ")
print('')
Additionally, it avoids using the index in the inner loop, which is usually considered more pythonic.
Upvotes: 0
Reputation: 64
Printing the length of just tableData will result in:
print(len(tableData))
3
But that is not correct because you want the number of rows in order to display it correctly, so you need to get the number of rows from the first list in the list.
print(len(tableData[0]))
4
And 4 is the number of rows.
Upvotes: 0
Reputation: 3852
The idea behind using tableData[0]
is just to get the length of each list, which in turn is the number of rows in your output. We usually use the first element because we assume the list is not empty. Then we use len(tableData)
to get the number of columns desired in the output. I've renamed one of your variables to make this more visible:
for row in range(len(tableData[0])): # Number of rows
for col in range(len(tableData)): # Number of columns
print(tableData[col][row], end = " ") # Print row elements separated by space
print('') # Jump to a new line when we're done with this row
Upvotes: 2
Reputation: 1173
Using len(tableData)
you would get the number of sublists contained in tableData, that in your case represents the number of output columns. To get the number of rows you measure the length of the first sublist (4) with len(tableData[0])
that in your output will represent the number of rows.
Upvotes: 1