Maegan Johnson Maegan Johnson - 1 month ago 5
Python Question

Why is my python list vertical?

Using python 3 and jupyter notebook (I have to, for class).

I have a function that creates a list by looping a number of times and appending a randomly chosen element from another list. But when I use the function, the list it gives displays each element on a new line. Why? Can I change it?

The code:

def create_board(length=32,seed=0,types=2):
"""
Creates a one-dimensional game board of randomly placed
letters, using as many as are specified.
"""

if types>26:
print("No, try a number smaller than 27.")

else:

board = []
letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]


for i in range(length):
val=random.randint(0,(types-1))
board.append(letters[val])


return board


And then both

print(create_board())


and

create_board()
board


put out the created list, but with each element on a new line:

['B',

'B',

'A',

'B',

'A',

and so on.

Answer

This is caused by pretty printing, which is turned on by default in IPython sessions. This can be turned off in the configuration options, or during the session itself by running the pprint magic:

In [12]: %pprint
Pretty printing has been turned OFF

In [13]: %pprint
Pretty printing has been turned ON

In [14]: %pprint
Pretty printing has been turned OFF
Comments