[Python] Strange behavior when partitioning list of tuples into different lists [duplicate]

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

  1. Stack

    Stack Membro Participativo

    I found some really unexpected behavior today using python 3.12.4. I am trying to sort a list of tuples into 2 different lists in a list of lists based on the first number of the tuple. Instead, each list in the list of lists gets every tuple.

    I see similar posts here:

    How to group a list of tuples/objects by similar index/attribute in python?

    List of Tuples to List of List of Tuples

    which suggests using defaultdict or itertools. But I would prefer to understand why what I am doing here does not work.

    Here is a minimal recreation of the problem

    data = [(0,1),(0,2),(1,1),(1,2),(1,3)]
    arr = [[]]*2

    for x in data:
    if x[0] == 0:
    arr[0].append(x)
    elif x[0] == 1:
    arr[1].append(x)
    print(arr)
    >>> [[(0, 1), (0, 2), (1, 1), (1, 2), (1, 3)], [(0, 1), (0, 2), (1, 1), (1, 2), (1, 3)]]


    Hence, each list in the list of lists is the same and gets every tuple. My expectation is that the code should return:

    >>> [[(0, 1), (0, 2)], [(1, 1), (1, 2), (1, 3)]]


    Can anyone explain why this is happening?

    Continue reading...

Compartilhe esta Página