This should work:
unknown_list = ["toby", "James", "kate", "George", "James", "rick", "Alex", "Jein", "Alex", "Alex", "George", "Jein", "kate", "medelin"]
for i in range(len(unknown_list)):
unknown_list[i] = unknown_list[i].upper()
print (unknown_list)
i = 0
n = len(unknown_list)
while i < n:
item = unknown_list[i]
if item in unknown_list[i+1:]:
unknown_list.remove(item)
n = n - 1
else:
i = i + 1
print (unknown_list)
Explanation:
Never remove elements from a list inside a for
loop. Never. You'll almost certainly end up with the index out of range
error. And even if you don't at least half the elements will be skipped.
One solution is to use a while
loop. Since the elements of the list are shifted to the left upon removal the trick is to only advance the i
index when no element is removed. On the other hand, if an element is removed you stay put (the unknown_list[i]
element will now be the shifted element to compare) and, of course, you decrease the total number of elements in the list (n
).
Please, make sure you understand what happens to the list after an item is removed. You can figure it out by looking at the order of the elements in the resulting list:
['TOBY', 'JAMES', 'RICK', 'ALEX', 'GEORGE', 'JEIN', 'KATE', 'MEDELIN']
compared to the input list:
['TOBY', 'JAMES', 'KATE', 'GEORGE', 'JAMES', 'RICK', 'ALEX', 'JEIN', 'ALEX', 'ALEX', 'GEORGE', 'JEIN', 'KATE', 'MEDELIN']