[Python] Dictionary creation with fromkeys and mutable objects. A surprise [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 27, 2025.

  1. Stack

    Stack Membro Participativo

    I came across this behavior that surprised me in Python 2.6 and 3.2:

    >>> xs = dict.fromkeys(range(2), [])
    >>> xs
    {0: [], 1: []}
    >>> xs[0].append(1)
    >>> xs
    {0: [1], 1: [1]}


    However, dict comprehensions in 3.2 show a more polite demeanor:

    >>> xs = {i:[] for i in range(2)}
    >>> xs
    {0: [], 1: []}
    >>> xs[0].append(1)
    >>> xs
    {0: [1], 1: []}
    >>>


    Why does fromkeys behave like that?

    Continue reading...

Compartilhe esta Página