You can invert the problem:
- print a sublist if it is the first one - without newline after it
- if it is not the first one, print a newline followed by the next sublist
that way your last line does not have to \n
at its end:
def matprint(r, c):
data = list(range(1,r*c+1))
l= [data[i*c:i*c+c] for i in range(r)]
formatter = ('{} ' * c).strip() # create the format string once - strip spaces at end
for i,sublist in enumerate(l):
if i: # 0 is False, all others are True
print("")
print( formatter.format( *sublist ), end="" ) # do not print \n at end
matprint(3, 5)
I optimized the code a bit as well - you should not use things like max,min,list,dict,...
as variable names - they hide the build in functions of the same name.
Your list construction can be streamlined by a list comprehension that chunks your numbers list - see How do you split a list into evenly sized chunks? .
You do not need to recompute the length of your sublist - it is c
long.
You need the index from enumerate()
to decide if the list is "first" - and you need the end=""
option of print to avoid autoprinting newlines.
A simpler version without enumerate could be done using list slicing:
def matprint(r, c):
data = list(range(1,r*c+1))
l= [data[i*c:i*c+c] for i in range(r)]
formatter = ('{} ' * c).strip() # create the format string once - strip spaces at end
print(formatter.format(*l[0]), end="") # print the 1st element w/o newline
for sublist in l[1:]:
# print all others including a \n in front
print( "\n"+formatter.format( *sublist ), end="" ) # do not print \n at end