scorpionz scorpionz - 3 months ago 13
Python Question

How to add a new line after each loop?

Currently getting this output

[1, 1, 3, '\n']
[1, 1, 3, '\n', 7, 7, 7, '\n']


looking for this output

[1, 1, 3]
[7, 7, 7]


Code:

import random
my_list=[]
n = 3
m = 1
while m < 10:
for i in range(n): # repeats the following line(s) of code n times
my_list.append(random.randrange(0,9))
my_list.append("\n")
print(my_list)
m = m+1

Answer
import random
n = 3
m = 0
my_list = []
while m < 10:
    my_list.append([])
    for i in range(n):
        my_list[m].append(random.randrange(0, 9))
    print(my_list[m])
    m = m + 1

This code creates sublists inside my_list, and prints out each sublist every iteration. So your output might be something like this:

[0, 4, 8]
[3, 1, 5]
...
[9, 2, 5]

but my_list would store all the sublists, like this: [[0, 4, 8], [3, 1, 5], ..., [9, 2, 5]]

Comments