AttributeError: 'list' object attribute 'append' is read-only

9.3k Views Asked by At

I am new to this world and I am starting to take my first steps in python. I am trying to extract in a single list the indices of certain values of my list (those that are greater than 10). When using append I get the following error and I don't understand where the error is.

dbs = [0, 1, 0, 0, 0, 0, 1, 0, 1, 23, 1, 0, 1, 1, 0, 0, 0, 
       1, 1, 0, 20, 1, 1, 15, 1, 0, 0, 0, 40, 15, 0, 0]

exceed2 = []

for d, i in enumerate(dbs):
    if i > 10:
        exceed2.append= (d,i)
        print(exceed2)
2

There are 2 best solutions below

5
Alex Kritchevsky On

You probably mean to write

for i, d in enumerate(dbs):
    if d > 10:
        exceed2.append(i)
print(exceed2)

Few fixes here:

  • append=() is invalid syntax, you should just write append()
  • the i, d values from enumerate() are returning the values and indexes. You should be checking d > 10, since that's the value (per your description of the task). Then you should be putting only i into the exceed2 array. (I switch the i and d variables so that i is for index as that's more conventional)
  • append(d,i) wouldn't work anyway, as append takes one argument. If you want to append both the value and index, you should use .append((d, i)), which will append a tuple of both to the list.
  • you probably don't want to print exceed2 every time the condition is hit, when you could just print it once at the end.
0
peter Nicola On

Welcome to this world :D

the problem is that .append is actually a function that only takes one input, and appends this input to the very end of whatever list you provide.

Try this instead:

dbs = [0, 1, 0, 0, 0, 0, 1, 0, 1, 23, 1, 0, 1, 1, 0, 0, 0,
       1, 1, 0, 20, 1, 1, 15, 1, 0, 0, 0, 40, 15, 0, 0]

exceed2 = []

for d, i in enumerate(dbs):
    if i > 10:
        exceed2.append(i)
        print(exceed2)