1

I am using python 3.7, and I need to modify multiple lists with the same set of ops - dedup & sort.

I wrote the below code, and can verify the lists are updated (with the print statements in the for loop) but the updates are lost outside of the loop (last print statement).

Here is my code:

for lst in list1, list2, list3, list4, list5:
    print(len(lst))  # shows the original count before dedup
    lst = list(set(lst))
    lst.sort()
    print(len(lst))  # shows the right count after dedup

print(list1) # shows the original list before dedup

I guess the for loop updates a copy of the list and not the original lists. I can run set and sort on the individual lists without a for loop but checking to see if there is a cleaner way to update tens of lists using a loop.

4
  • Modifying the original array while looping through it is always a bad idea. Map fns might be a good choice. Commented Jul 6, 2020 at 19:12
  • Please provide a minimal reproducible example, as well as the current and expected output. Commented Jul 6, 2020 at 20:18
  • 1
    Nice work creating a well thought out problem. You get used to name binding rules after a while, but it's confusing as a beginner. Good job posting an MCVE that not only illustrates the problem, but shows that you've made a real attempt to trace the problem and debug on your own. Welcome to SO! Commented Jul 7, 2020 at 1:48
  • 1
    By the way, if you have tens of lists, consider keeping them in a list or dict. Commented Jul 7, 2020 at 1:49

1 Answer 1

2

lst = rebinds the name lst so it's no longer referencing the same object. To avoid rebinding, you can overwrite the contents of the list:

lst[:] = set(lst)
Sign up to request clarification or add additional context in comments.

1 Comment

Although the in-place operation avoids making a third copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.