When I run the following code, I get an error:
def genSet(nums):
for i in range(0, len(nums)-1):
for x in range(0, len(nums)-1):
if nums[x] == nums[i]:
del nums[x]
return nums
a = [5, 4, 3, 5, 6, 7, 8, 5, 4, 3]
print genSet(a)
Output:
Traceback (most recent call last):
File "49.py", line 9, in <module>
print genSet(a)
File "49.py", line 4, in genSet
if nums[x] == nums[i]:
IndexError: list index out of range
As far as I can tell (I replaced the if statement with “print x, i”) the two for loops are fine, so why is the index out of range?
don’t do
del nums[x], since this way you makenumsshorter and thus get an exception.you can simply make a set out of the list by
set_nums = set(nums)