2

I'm fairly new to Python and having a hard time figuring out how to print a list in rows given these circumstances:

The list starts out empty and the computer generates random 2-digit integer entries, which are then appended to the list. Printing the list is easy enough, either in a single column or in a single line using

for i in list:
    print(i, end = "")

but what I want to do is print in rows of 4, ending the list with whatever the remainder is (e.g. a row of 3), so that the outcome would look something like this:

81  27  19  55
99  45  32  90
67  83  20  72
12  86  21

What is the best and most straightforward way to do this?

Edit: I forgot to clarify that I'm working in Python 3. Sorry about that.

chrono
  • 67
  • 1
  • 1
  • 3
  • I guess pprint is a good catch https://docs.python.org/2/library/pprint.html#pprint.PrettyPrinter Try playing with the width argument of the constructor – mitsest Feb 25 '16 at 22:45
  • Divide your list into chunks of 4 ([link 1](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python), [link 2](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks)), and print each chunk on a line. – gil Feb 25 '16 at 22:48

5 Answers5

3

There many ways to do this, as others have shown. One more:

for i in range(0, len(mylist), 4):
    print(*mylist[i:i+4], sep=' ')
gil
  • 2,086
  • 12
  • 13
2

You could use the modulus operator to recognize when you're on the 4th column and change the end value to print.

for i, val in enumerate(list):
    end = '\n' if (i + 1) % 4 == 0 else '  '
    print(val, end=end)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
1

Just add a statement to drop in a newline every 4th item:

count = 1
for i in list:
    print(i, end = "")
    count += 1
    if count % 4 == 0:
        print('\n')

If you like indexing better:

for i in len(list):
    print(list[i], end = "")
    if i % 4 == 0:
        print('\n')

Does that solve the problem for you?

Prune
  • 76,765
  • 14
  • 60
  • 81
1
for ind, val in enumerate(yourList):
    if ind != 0 and ind % 4 == 0:
        print('\n')
    print(val, end=' ')
DevShark
  • 8,558
  • 9
  • 32
  • 56
0

If this is your starting list of numbers:

numbers = [81, 27, 19, 55, 99, 45, 32, 90, 67, 83, 20, 72, 12, 86, 21]

I would first group them into separate lists:

grouped_numbers = [numbers[i:i+4] for i in range(0,len(numbers),4)]

Then I would print out each group with a blank space in between them using the join function

for group_of_numbers in grouped_numbers:
    print (" ".join(map(str,group_of_numbers)))
Coline Do
  • 96
  • 2