I am just testing out how lists work in python and I find it to be very confusing and frustrating. For whatever reason I am getting constant error messages on my code.
def listtest(list1,x):
list2 = []
count = 0
for n in list1:
if list1[count] == x:
count += 1
else:
list2 = list.append(list2,list[count])
count += 1
return list2
For whatever reason it is either telling me that list.append only accepts one argument which is confusing. In the interactions window I can call append with two arguments like so list.append(list,3) or whatever and it works flawlessly. The other error I am getting is
list2 = list.append(list2,list[count])
TypeError: 'type' object has no attribute '__getitem__'
which is entirely nonsensical to me and not in any way helpful. What is wrong with my code? Why does the interactions window behave differently than the other window? Why won’t append work like it does in the interactions window?
Edit: Rewritten after some more careful analysis:
Your immediate problem is
list[count]which should belist1[count]. The built-in typelistcan’t be indexed (since it’s a type, not a list), so you get theTypeErrorabout the__getitem__()method not being supported.But even if you had written
list2 = list.append(list2,list1[count]), you’d still have a problem. What would that line of code do?list1[count]tolist2. So far, so good.list.append()tolist2. Since.append()is a method that modifies the object it’s called on in-place, it always returnsNone.list2isNone.TypeErrorbecause you can’t append anything toNoneTypeobjects.So, what you should have written is
While that would now work, it’s an extremely roundabout way to do this. Keeping track of indexes you don’t actually need is very unpythonic – the language is much more expressive than that. Don’t try to write Java programs in Python. Your function (if your aim really is to create a new list that contains all the objects in
list1that are the same asx– for which I fail to see the point entirely) could be written asalthough that’s not much more useful than simply writing
which gives you the number of times
xappears inlist1.