0

I am trying to convert the display the content of the list such that only three elements print in each line, and able to write the below code using if/else, which is working as expected..

lst = ["s1","s2","s3","s4","s5","s6","s7","s8"]

cnt=0
var4=""

for i in range(len(lst)):
    if (cnt%3) == 0:
        var4 = var4 + "\n" + lst[i]
    else:
        var4 = var4 + ", " + lst[i]
    cnt +=1 
    
print(var4)

Output:

s1, s2, s3
s4, s5, s6
s7, s8

Trying to find if the same result can be achieved using List Comprehension or some other efficient possible way.

thanks..!!

Sandy
  • 419
  • 1
  • 8
  • 15
  • print(("".join(["{0} {1}".format(element, "\n") if (index+1) % 3 == 0 else "{0}, ".format(element) for index, element in enumerate(lst)]))) – can Nov 21 '20 at 03:32
  • 1
    `print(''.join(v + (', ' if i%3 else '\n') for i,v in enumerate(["s1","s2","s3","s4","s5","s6","s7","s8"], start=1)).rstrip(', '))` but that's not an improvement over normal style. – TigerhawkT3 Nov 21 '20 at 03:34
  • 1
    Who closed this? This is not even related to splitting the list into equally sized chunks. Not as long as what OP wants. – Tsubasa Nov 21 '20 at 03:41

1 Answers1

0

Not sure if this is what you're looking for, but here's a solution using list comprehension with join.

lst = ["s1","s2","s3","s4","s5","s6","s7","s8"]

block_size = 3

lines = [", ".join(lst[i:min(len(lst), i + block_size)]) for i in range(0, len(lst) + block_size, block_size)]

print("\n".join(lines))