Appending to a list gives ‘int’ object has no attribute ‘append’

Traceback (most recent call last): File "/home/shinigami/prac5.py", line 21, in a[i].append(p) AttributeError: 'int' object has no attribute 'append'

Your variable a is a list of integers. When you write a[i].append(...) you’re trying to call an append method on an int type, which causes the error.

Writing a.append(...) is fine because a is a list, but as soon as you index into the list, you’re dealing with with the numbers within the list, and they have no append method. For example:

>>> a = [i for i in range(5)]
>>> a
[0, 1, 2, 3, 4]
>>> a.append(5)
>>> a
[0, 1, 2, 3, 4, 5]
>>> a[2].append(6)   # won't work!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'append'

Simply make sure you’re using the correct types. The logic in your code is currently very complicated, so you should simplify it.

Also Let me know is their a another way to make a 2D LIST

You can use list comprehensions. For example:

>>> from pprint import pprint as pp
>>> dim = 2     # take user input here
>>> matrix = [(i, j) for i in range(dim) for j in range(dim)]
>>> pp(matrix)
[(0, 0), (0, 1), (1, 0), (1, 1)]
#
# Index into the matrix as you normally would.
#
>>> matrix[1][0]
0
>>> matrix[1][1]
1

The above was tested using Python3, but you can adapt it to Python2 if necessary.

Leave a Comment