How to decrease the line spacing in this python program?

Viewed 221

I was learning nested loops, and ran into this problem with line spacing between each of x's lines.

numbers = [2, 2, 2, 2, 7, 7]

for i in numbers:
    for j in range(0, i):
        print("x", end='')
    print('\n')

Following is the output of my code:

xx

xx

xx

xx

xxxxxxx

xxxxxxx

What changes should I make in my code so that an additional line is not present between each x's line?

3 Answers

Replace print("\n") with print(), as print already prints a trailing newline by default.

This is working, I have tried

numbers = [2, 2, 2, 2, 7, 7]

for i in numbers:
    for j in range(0, i):
        print("x", end='')
    print()

Best of luck.

A simple solution to avoid an unnecessary inner for loop:

numbers = [2, 2, 2, 2, 7, 7]

for i in numbers:
    print('x' * i)

An alternative with f-strings:

filler = 'x'
for i in numbers:
    print(f'{filler:{filler}<{i}}')

If you wanted you could also do this in a single print statement (without loops) using a built-in like map:

print(*map(lambda i: 'x' * i, numbers), sep='\n')
Related