‘nonetype’ object has no attribute ‘append’ – Python Error

Total
0
Shares

Python throws error ‘nonetype’ object has no attribute ‘append’ when we try to store the outcome of append in the array. Let’s understand this with an example –

superHeroArray = []
superHeroArray = superHeroArray.append('Captain America')

This code will throw error because append updates the original array. Just like insert, remove, sort etc. it modifies the array and return the default in Python which is None.

The correct way of using append and our code example is –

superHeroArray = []
superHeroArray.append('Captain America')

There is no need to store the result of append to input array because append will return None and superHeroArray will loose the array reference and store None in it.

You can do that same thing without using append function. Check this code –

superHeroArray = []
superHeroArray[len(superHeroArray):] = ['Captain America']

    Tweet this to help others

According to Python documentation, these functions do not return anything –

  • list.append(x)
  • list.insert(i,x)
  • list.remove(x)
  • list.clear()
  • list.reverse()
  • list.sort()

Live Demo

Open Live Demo