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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started