-4

This is my python code:

d = []
for x in range(5):
d.append(["O"] * 5)
print d

and output is:

[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]

but I want the output as follows:

['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O'] 

Eventually like this:

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
2
  • Are you trying to create a matrix? Commented Oct 7, 2018 at 8:00
  • You can make it simplest with numpy: import numpy as np and d=np.zeros((5,5)) Commented Oct 7, 2018 at 8:10

1 Answer 1

1

The first one happens like this, if you just print(d) you will print the entire list but by looking at the desired output, we can tell we only want one sublist per line. So we loop through d and print each sublist i on its own line

d = []
for i in range(5):
    d.append(['0']*5)

for i in d:
    print(i)
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '0']

For the second part its the same concept except we use * to unpack the items.

for i in d:
    print(*i)    
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Sign up to request clarification or add additional context in comments.

2 Comments

I write this code on tutorialspoint.com/execute_python_online.php : d = [] for x in range(5): d.append(["O"] * 5) for i in d: print (*i) but i receive SyntaxError for *i
@omid it probably has to do with the online compiler

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.