[Python] Python list copy and slice modifying original list

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list as shown below:

    voting_records = [['1.', 'DIRECTOR', 'Management'],
    ['1', 'Allison Grant Williams', 'For'],
    ['2', 'Sheila Hartnett-Devlin', 'For'],
    ['3', 'James Jessee', 'For'],
    ['4', 'Teresa Polley', 'For'],
    ['5', 'Ashley T. Rabun', 'For'],
    ['6', 'James E. Ross', 'For'],
    ['7', 'Rory Tobin', 'For']]


    I created a copy of this list named voting_records_short using list comprehension:

    cnames = ["Record","Proposal","Sponsor","VoteCast"]
    voting_records_short = [record for record in voting_records if len(record) < len(cnames)]


    Then I created a slice of voting_records_short and save it in directors. I then modify the directors list in a for loop as shown below:

    if len(voting_records_short) == 0: pass
    else:
    ifdirector = ["DIRECTOR" in record for record in voting_records_short]
    if True in ifdirector:
    directorindx = int(ifdirector.index(True))
    directorline = [voting_records_short[directorindx]]
    directors = voting_records_short[directorindx+1:]
    sponsoridx = cnames.index("Sponsor")
    for ls in range(len(directors)):
    directors[ls][0] = directorline[0][0] + directors[ls][0]
    directors[ls][1] = directorline[0][1] + " " +directors[ls][1]
    directors[ls].insert(sponsoridx,directorline[0][-1])


    Why does modifying directors list in the for loop modifies both the voting_records_short list and voting_records as shown in the outputs below:

    In [2]: voting_records
    Out[2]:
    [['1.', 'DIRECTOR', 'Management'],
    ['1.1', 'DIRECTOR Allison Grant Williams', 'Management', 'For'],
    ['1.2', 'DIRECTOR Sheila Hartnett-Devlin', 'Management', 'For'],
    ['1.3', 'DIRECTOR James Jessee', 'Management', 'For'],
    ['1.4', 'DIRECTOR Teresa Polley', 'Management', 'For'],
    ['1.5', 'DIRECTOR Ashley T. Rabun', 'Management', 'For'],
    ['1.6', 'DIRECTOR James E. Ross', 'Management', 'For'],
    ['1.7', 'DIRECTOR Rory Tobin', 'Management', 'For']]

    In [9]: voting_records_short
    Out[9]:
    [['1.', 'DIRECTOR', 'Management'],
    ['1.1', 'DIRECTOR Allison Grant Williams', 'Management', 'For'],
    ['1.2', 'DIRECTOR Sheila Hartnett-Devlin', 'Management', 'For'],
    ['1.3', 'DIRECTOR James Jessee', 'Management', 'For'],
    ['1.4', 'DIRECTOR Teresa Polley', 'Management', 'For'],
    ['1.5', 'DIRECTOR Ashley T. Rabun', 'Management', 'For'],
    ['1.6', 'DIRECTOR James E. Ross', 'Management', 'For'],
    ['1.7', 'DIRECTOR Rory Tobin', 'Management', 'For']]



    I was expecting that only the directors list will be modified (and maybe voting_records_short but I'm not sure) but why is the original voting_records list modified? I'd appreciate any help?

    Continue reading...

Compartilhe esta Página