[Tutor] List issues

Peter Otten __peter__ at web.de
Thu Apr 17 10:17:49 CEST 2014


Wheeler, Gabriel wrote:

> Im having trouble completing this function with lists. Im supposed to
> create a function that will let me know if there are repeating elements so
> I wrote this and am not sure where the error lies. 

It helps you (and us) a lot if you clearly state the error you are seeing. 
If your script bails out with an error post the complete traceback. If all 
appears to be working, but you get a wrong or unexpected result say what you 
get and what you expected. 

Running your code I get

$ cat check_dupes.py 
list = [1,2,2,2,3,4]

def duplicate(list):
    for i in range(len[list]):
        if list.count(i) > 1:
            return True

print duplicate(list)
$ python check_dupes.py 
Traceback (most recent call last):
  File "check_dupes.py", line 8, in <module>
    print duplicate(list)
  File "check_dupes.py", line 4, in duplicate
    for i in range(len[list]):
TypeError: 'builtin_function_or_method' object has no attribute 
'__getitem__'

Looking at the line shown in the traceback

    for i in range(len[list]):

what could be the function you are not calling but asking for that strange 
__getitem__ attribute? Hint:

>>> def hello(name):
...     print "Hello,", name
... 
>>> hello("Gabriel")
Hello, Gabriel
>>> hello["Gabriel"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object has no attribute '__getitem__'

That sure looks similar to your error message.

Once you have fixed that I recommend that you add a print statement

def duplicate(list):
    for i in range(len[list]): # must be fixed
        print "looking for", i
        if list.count(i) > 1:
            return True

You'll see that you are looking for items that are not in the list? Can you 
figure out why?

If not, call the function with another list

duplicate(["a", "b", "b", "b", "c", "d"])

> It is supposed to count
> the number of times a number appears and if its greater than 1 then it
> will say True.
> 
> 
> #Problem 3
> 
> list = [1,2,2,2,3,4]
> 
> def duplicate(list):
>     for i in range(len[list]):
>         if list.count(i) > 1:
>             return True
> 
> 
> print duplicate(list)




More information about the Tutor mailing list