Search code examples
pythonoperation

Why does the comma symbol in Python return true?


I am wondering why the comma symbol "," returns true:

mutant = toolbox.clone(ind1)
ind2, = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
print (ind2 is mutant)
>>>True

But when I remove the comma symbol:

ind2 = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
print (ind2 is mutant)
>>>False

it returns false. It would be very thankful if anyone could explain the mechanism behind this.


Solution

  • The deap.tools.mutGaussian() function you are calling returns a tuple containing a single value:

    Returns: A tuple of one individual.

    When you leave off the comma, you are assigning the resulting tuple to a single variable.

    With the comma, you are asking Python to unpack the iterable on the right-hand-side into a series of names on the left; because both the left-hand side and the right-hand-side have just one element, this work. You unpacked the value in the returned tuple into a single variable.

    See the Assignment statements reference documenation:

    An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

    If you wanted to test that single value without using iterable assignment, you'll have to manually get that one value out of the tuple:

    ind2 = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
    print(ind2[0] is mutant)
    

    Note the [0] indexing.