0
def group_by_owners(files):
    fin2=[]#creating list
    fin={}#creating dictionary
    for v in files.values():#looping the values of a dictionary
        for m,n in files.items():#looping the keys of dictionary
            if n==v:
                fin2.append(m)#appending all file_name which belong to owner
        fin[v]=fin2#storing in dictionary
        fin2.clear()#the line where i have used clear() function   
    return fin
files = {'Input.txt': 'Randy','Code.py': 'Stan','Output.txt': 'Randy'} #file_name:Owner  
group_by_owners(files)
print(group_by_owners(files))

output:{'Randy': [], 'Stan': []}

def group_by_owners(files):
    fin2=[]
    fin={}
    for v in files.values():
        for m,n in files.items():
            if n==v:
                fin2.append(m)
        fin[v]=fin2
        fin2=[] #line where i have reinitialized the list as empty  
    return fin
files = {'Input.txt': 'Randy','Code.py': 'Stan','Output.txt': 'Randy'}   
group_by_owners(files)
print(group_by_owners(files))

output:{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}

Both clear() function and list=[] Do The Same Job Of Emptying The List Then Why Does it Give A Different Output

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Rohit
  • 1
  • `f2.clear()` mutates the list, changing not just it but any other references to it - which in your case, is every element of the dictionary. Whereas `f2 = []` simply assigns a new (empty) list to the variable, leaving the other references to the previous list intact. – Robin Zigmond Nov 25 '20 at 20:10
  • 1
    "Both clear() function and list=[] Do The Same Job Of Emptying The List" *no they absolutely do not*. `fin2.clear()` empties the list being referred to by `fin2`. `fin2 = []` **assigns a new, empty list to the variable `fin2`. – juanpa.arrivillaga Nov 25 '20 at 20:10
  • Thankyou so much for the explanation!! – Rohit Nov 25 '20 at 20:20

2 Answers2

2

Both clear() function and list=[] Do The Same Job Of Emptying The List

The observation that clear() and = [] do the same thing is wrong. They both give you an empty list, but not in the same way.

clear() clears the list. The same list. Since you are doing fin[v]=fin2, fin2.clear also clears fin[v] because fin[v] and fin2 point to the same list.


= [] creates a new list.

fin[v] = fin2
fin2 = []

fin[v] points to the same list fin2 points to, but then fin2 is pointing to a brand new list that has nothing to do with fin[v].

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

fin2 = [] assigns a new (empty) list to the fin2 variable, and does not affect any other reference to the old list.

fin2.clear() preserves the list reference but removes all the elements from it.

In the first snippet, all the elements of the dictionary point to the same list instance, which is cleared on every iteration.

Mureinik
  • 297,002
  • 52
  • 306
  • 350