Reputation: 51
How to display 5 numbers per line from a list?
lx = [1,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
def display(lx):
for i in range(0,len(lx), 5):
x = lx[i:i +5]
return x
print(display(lx))
my current code is displaying only one line that contains 5 numbers, and the expected should be 5 lines that contains 5 numbers per line
Upvotes: 1
Views: 1206
Reputation: 48
lst = [55, 26, 59, 35, 28, 22, 33, 43, 49, 45, 20, 11, 34, 44, 57, 12, 16, 31, 32, 58, 15, 38, 37, 48, 39]
def display(lst):
x = 0
while x in range(len(lst)):
print(lst[x:x+5])
x+=5
#Output
[55, 26, 59, 35, 28]
[22, 33, 43, 49, 45]
[20, 11, 34, 44, 57]
[12, 16, 31, 32, 58]
[15, 38, 37, 48, 39]
Upvotes: 1
Reputation: 211
There can be different approaches to the problem:
x=[] #your given list
for t in range(len(x)):
if(t%5==0):
print('\n')
print(str(x[t])+'\t',end='') #end will print numbers on same line otherwise
this code will give the desired output..
Upvotes: 0
Reputation: 41
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
def printer(lis, num_per_line):
z = 1
for each_num in lis:
if z%(num_per_line) == 0:
print(each_num, end='\n')
else:
print(each_num, end='\t')
z+=1
printer(x, 5)
Use this function where you need to pass the list and entities to be printed in a single line.
The output is:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
Upvotes: 1
Reputation: 106533
You can make the function a generator by making it yield the sliced lists instead:
def display(lx):
for i in range(0, len(lx), 5):
yield lx[i:i + 5]
print(*display(lx), sep='\n')
This outputs:
[1, 2, 4, 5, 6]
[7, 8, 9, 10, 11]
[12, 13, 14, 15, 16]
[17, 18, 19, 20, 21]
[22, 23, 24, 25]
Upvotes: 7