Search code examples
pythonsetlist-comprehensionpython-3.5

List comprehension against tuple of sets


Can someone please explain what is going on?

>>> xx = ({1,2}, {2,3}, {3,4}, {4,2})
>>> yy = [x.discard(2) for x in xx]
>>> yy
[None, None, None, None]
>>> xx
({1}, {3}, {3, 4}, {4})
>>> id(xx)
4315823704
>>> id(yy)
4315797064

I'd expected yy to be equal to [{1}, {3}, {3, 4}, {4}] and xx to remain untouched!


Solution

  • To obtain the result that you want, you could use a list comprehension of the form:

    yy = [x - {2} for x in xx]
    

    For example:

    >>> xx = ({1,2}, {2,3}, {3,4}, {4,2})
    >>> yy = [x - {2} for x in xx]
    >>> yy
    [{1}, {3}, {3, 4}, {4}]
    >>> xx
    ({1, 2}, {2, 3}, {3, 4}, {2, 4})
    

    Your original example behaves as follows:

    >>> xx = ({1,2}, {2,3}, {3,4}, {4,2})
    >>> yy = []
    >>> for x in xx:
    ...   # Here, x is a reference to one of the existing sets in xx.
    ...   # x.discard modifies x in place and returns None.
    ...   y = x.discard(2)
    ...   # y is None at this point.
    ...   yy.append(y)
    ...
    >>> yy
    [None, None, None, None]
    >>> xx
    ({1}, {3}, {3, 4}, {4})