user2728024
user2728024

Reputation: 1546

Python append replaces the existing list with None

Please have a look at this program.

The append function replaces the list with None. The error is attached below

class Solution(object):
     def isIsomorphic(self, a, b):

        ad = {} 
        bd = {}
        if len(a) != len(b):
             return False 
        for i in range(len(a)):
             if a[i] in ad:
                 ad[a[i]] = ad[a[i]].append(i)  
            else:
                ad[a[i]] = [i]

            if b[i] in bd:
                 bd[b[i]] = bd[b[i]].append(i)           
            else:
                 bd[b[i]] = [i]
         ret = True 
         for j,k in zip(ad.values(), bd.values()):
             if j != k:
                return False 
         return ret 


sol = Solution()
print sol.isIsomorphic("ccc", "aab")  
ERROR
     ad[a[i]] = ad[a[i]].append(i)

 AttributeError: 'NoneType' object has no attribute 'append'     

Upvotes: 0

Views: 91

Answers (2)

Sunnysinh Solanki
Sunnysinh Solanki

Reputation: 551

Here you go: you were assigning ad[a[i]].append[i] to ad[a[i]] which was not needed. It's function call and returns None. You just need to do ad[a[i]].append(i)

class Solution(object):
 def isIsomorphic(self, a, b):

    ad = {} 
    bd = {}
    if len(a) != len(b):
         return False 
    for i in range(len(a)):
        if a[i] in ad:
             ad[a[i]].append(i)  
        else:
            ad[a[i]] = [i]


        if b[i] in bd:
             bd[b[i]].append(i)           
        else:
             bd[b[i]] = [i]
    ret = True 
    for j,k in zip(ad.values(), bd.values()):
        if j != k:
            return False 
    return ret 

sol = Solution() print sol.isIsomorphic("ccc", "aab")

Upvotes: 0

atru
atru

Reputation: 4744

append appends the value to the list in place and returns None. So ad[a[i]] = ad[a[i]].append(i) means you're replacing ad[a[i]] with None.

Here is the part of documentation that states it

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python.

Upvotes: 1

Related Questions