0

So I needed to define a function that receives a list containing letters and returns a new list with all the positions of a given letter, e.g. lst = ['a', 'b', 'c'] if letter = 'a' then [0]. In my code I get

    res=res.append(finallist)
AttributeError: 'NoneType' object has no attribute 'append'

What did I do wrong?

def  searchlist(lst,letter):
   res=[]
   for i in range(len(lst)):
     finallist=lst.index(letter)
     res=res.append(finallist)
   return res
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    Does this answer your question? [Python Append to a list returns none](https://stackoverflow.com/questions/28110161/python-append-to-a-list-returns-none) – Rakesh Dec 03 '19 at 07:57
  • Remove `res =` from `res = res.append(finallist)` and you should be fine – rivamarco Dec 03 '19 at 08:13

2 Answers2

1

You should change res=res.append(finallist) into res.append(finallist)

Because res.append(finallist) will not return a 'list' object, but just the success of that line of code, which is a 'NoneType' object. (actually it returns nothing.)

Now your code will look like this:

def searchlist(lst, letter):
    res = []
    for i in range(len(lst)):
        finallist = lst.index(letter)
        res.append(finallist)
    return res

However, even though you run this code, your program will not give you a result what you want, e.g. lst=['a', 'b', 'c'] if letter='a' then [0, 0, 0].

You'd better use the code below to get a result what you want.

def searchlist(lst, letter):
    res = []
    for i, element in enumerate(lst):
        if element == letter:
            res.append(i)
    return res


test_result = searchlist(['a', 'b', 'c', 'a'], 'a')
print(test_result)

Or you can make your code much more simple and cooler (which is preferable) by this way:

def searchlist(lst, letter):
    return [i for i, element in enumerate(lst) if element == letter]


test_result = searchlist(['a', 'b', 'c', 'a'], 'a')
print(test_result)

We call this technique as "list comprehension"

I got this idea from https://stackoverflow.com/a/16685428/8423105

Good luck.

kimDragonHyeon
  • 414
  • 5
  • 9
0

As rivamarco said in the comments you just have to remove res = from your code, because when you append an element to a list you're not making an assignment.