Question: With out taking any additional memory, how can I modify a list in place using a loop in python? I'm trying to delete all duplicates.

With out taking any additional memory, how can I modify a list in place using a loop in python? I'm trying to delete all duplicates. However, I keep getting "indexError: list index out of range". Before the index goes out of range, the modified list looks like this: nums=[0,1,1,2,2,3,3,4]. Like you can see, it still has duplicates. Can you please help me see how I can handle the index out of range and make sure all duplicates are gone. (I cannot use set()). Only loop through the list somehow. I think the list gets smaller as it gets modified, making it goes out of range. However, I'm not sure how to handles this situation.

This is my code: nums=[0,0,1,1,1,2,2,3,3,4] j=0 for i in range(1, len(nums)-1): if nums[i] == nums[j]: nums.pop(j) j+=1 print(nums)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!