+ 2

Error in Code

So I was writing a program in which few numbers had to be entered and those numbers needed to be checked for duplicates. Here's the code I wrote: class prog1: def main(): print("Enter 5 numbers \n") a = list(5) for i in range(0,5): a[i] = int(input()) c = 0 for i in range(0,5): for j in range(0,5): if (a [i] == a[j]): c+=1 break if (c>0): print("Duplicate numbers in list") else: print("No duplicate numbers in list") However, I keep receiving this error: Traceback (most recent call last): File "<pyshell#46>", line 1, in <module> prog1.main() File "D:/Installed/IDLE/Practice/prog1.py", line 4, in main a = list(5) TypeError: 'int' object is not iterable Could anyone help me with the error?

27th Feb 2018, 2:26 PM
Arpan Sircar
Arpan Sircar - avatar
3 odpowiedzi
+ 3
https://code.sololearn.com/c30x54O2JENO/#py print("Enter 5 numbers \n") numList = list() # create a blank list numDuplicates = 0 # count how many dupes for i in range(0,5): numList.append(int(input())) # since list is empty, append instead numDuplicates = (len(numList) - len(set(numList))) if (numDuplicates > 0): print("%d duplicate number(s) in list." % numDuplicates) else: print("No duplicate numbers in list.") len(numList) - len(set(numList)) ^That snippet right there is how we're checking duplicates more easily. First we get the length of the list itself, and then we get the length of the list after all duplicates are removed. Set() is the method that removes duplicates from the list. If result is 0 then that means length was the same between both sides of the equation, which means no duplicates were removed, which means no duplicates were found. So we just check if it's greater than 0 and if it is, then there were duplicates. As well, this value will let us know exactly how many duplicates too.
27th Feb 2018, 3:09 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
https://code.sololearn.com/chxRaRmbjvw6 Here you go. I hope you're comfortable, or would you like a drink to go with the link?
27th Feb 2018, 2:43 PM
Arpan Sircar
Arpan Sircar - avatar
+ 1
You're using the list constructor incorrectly. The list constructor takes in an iterable (string, tuple, dictionary, set). 5 is not an iterable. If you leave the argument empty it will return an empty list. Then you can use the lists append() method to add elements to the list. Also your nested for loop has a logic error comparing the first element of the list to the first element of the list will break from the loop and always say there are duplicate elements within the list.
27th Feb 2018, 3:06 PM
ChaoticDawg
ChaoticDawg - avatar