-1

(x_train, y_train), (x_test, y_test) = mnist.load_data()

This is tensorflow example, but I can't understand what it means I know purpose of x_train, y_train, x_test, y_test but I want to know how those are assigned. What kind of mechanism it is. Thank you

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • Does this answer your question? [How does Python return multiple values from a function?](https://stackoverflow.com/questions/39345995/how-does-python-return-multiple-values-from-a-function) – Dr. Snoopy Mar 15 '21 at 09:40

2 Answers2

5

It's called tuple or iterable unpacking. mnist.load_data() must return a sequence of two two-tuples:

>>> (x_train, y_train), (x_test, y_test) = [(1,2),(3,4)]
>>> x_train
1
>>> y_train
2
>>> x_test
3
>>> y_test
4

It can be used to unpack nested sequences:

>>> a,b,c = 1,2,3      # a=1,b=2,c=3
>>> (a,b),c = (1,2),3  # same

Use * to operate on varying sizes of sequences:

>>> a,*b = 1,2,3,4,5
>>> a
1
>>> b
[2, 3, 4, 5]

>>> a,*b,c = 1,2,3,4,5
>>> a
1
>>> b
[2, 3, 4]
>>> c
5

References::

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1

From the documentation of the mnist.load_data(), you can see that the return is:

Returns
Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test).

This means it returns two tuples, one for x and one for y.

In general, if a function returns two values, like:

def fun():
    return a,b

You can get the results like this: x,y = fun()

Here, the function mnist_load() is of the form:

def mnist_load():
    return (x_train,y_train), (x_test,y_test)

As others have said, this is called tuple unpacking.

Dharman
  • 30,962
  • 25
  • 85
  • 135
VincFort
  • 1,150
  • 12
  • 29