25

What is the difference between an iterable and an array_like object in Python programs which use Numpy?

Both iterable and array_like are often seen in Python documentation and they share some similar properties.

I understand that in this context an array_like object should support Numpy type operations like broadcasting, however Numpy arrays area also iterable. Is it correct to say that array_like is an extension (or super-set?) of iterable?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
dtlussier
  • 3,018
  • 2
  • 26
  • 22

2 Answers2

31

The term "array-like" is indeed only used in NumPy and refers to anything that can be passed as first parameter to numpy.array() to create an array.

The term "iterable" is standard python terminology and refers to anything that can be iterated over (for example using for x in iterable).

Most array-like objects are iterable, with the exception of scalar types.

Many iterables are not array-like -- for example you can't construct a NumPy array from a generator expression using numpy.array(). (You would have to use numpy.fromiter() instead. Nonetheless, a generator expression isn't an "array-like" in the terminology of the NumPy documentation.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Great - thanks. That clears it up, especially the link between `array-like` and the first arg of `numpy.array()`. – dtlussier Nov 21 '11 at 19:45
  • 1
    "All array-like objects are iterable" - this is not correct. Scalar value of ```int``` type is array-like and can be passed to ```numpy.array()```, but it is not iterable. – wombatonfire Nov 20 '16 at 15:58
  • 1
    @wombatonfire Yup, that's true. Even actual 0-d arrays can't be iterated, while they are clearly "array-like". They are even arrays. – Sven Marnach Nov 20 '16 at 20:52
5

While the first part of the Sven's answer is correct, I would like to add that array-like objects should not necessarily be iterable.

For example, in my particular situation I was interested in using numpy.rint() function that accepts array-like objects with scalars of type int. They are not iterable, but they are accepted. You can also pass ints to numpy.array(), so they are array-like.

Here is the confirmation from the "NumPy-Discussion" mailing list: https://mail.scipy.org/pipermail/numpy-discussion/2016-November/076224.html

wombatonfire
  • 4,585
  • 28
  • 36