1

I was experimenting with numpy arrays, I had this very simple example:

list = [2, 3]
list.append(np.array([3.2, 9.0, 7.6]))

And if I do print(list), it prints: [2, 3, array([3.2, 9. , 7.6])]

But if I do print(list[-1]), it prints only [3.2 9. 7.6] Can anyone expalin this for me, that if I print the numpy array as the last element of my python list, why does it print without the "array", the brackets, and the comas between the numbers? Many thanks

3 Answers3

4

Objects in python generally have two different methods that return a string representation of themselves for print.

They are __str__() and __repr__(), and they have different uses that you can read about here.

To print something you first have to convert it to a string. Normally print will attempt to use __str__ to make this conversion.

Doing print on a list results in a call on list.__str__(), which then tries to convert all it's internal elements into a string for printing. The call the list uses to convert these elements is __repr__().

So when you print a list, the list gets the __repr__ of each element, but when you print just that element, the print gets the __str__ of that element.

What you're seeing is the difference between __repr__ and __str__ in a numpy array.

x = np.array([1, 2, 3])
x.__str__()
x.__repr__()

Output:

'[1 2 3]'
'array([1, 2, 3])'
Primusa
  • 13,136
  • 3
  • 33
  • 53
1

It seems that it is because print function implicitly calls __str__ on its args.

But if you embedd an object in a list, to represent what is in the list, __repr__ will be call for all elements inside the list:

a = np.linspace(0, 10, 11)
print(a)
# [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]
print(repr(a))
# array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])

what you can do is cast the array to a list when printing and the array won't show up:

print([a])  # not good
# array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
print([list(a)])  # better
# [[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]]
Thibault D.
  • 1,567
  • 10
  • 23
1

This is because a numpy array when it's printed looks like a list.

But try this:

>>> import numpy as np

>>> l = [2, 3]
>>> l.append(np.array([3.2, 9.0, 7.6]))
>>> isinstance(l[-1], list)
False
>>> l2 = [3, 2]
>>> isinstance(l2, list)
True

And you will test that the array is not actually a list.