Reputation: 3
I am new at learning python and programming overall and I wonder which of these 2 codes is more efficient to the next problem:
Write a program to remove the duplicates on an existing list.
The first code is the one I managed to build without using another variable which takes memory(?), I know that building a nested loop takes alot of memory but isn't it different because I used "while" loop and it's only for deleting numbers.
List = [5,2,9,1,7,2,2,3,9]
for item in List:
while(List.count(item) >= 2):
List.remove(item)
print(List)
List = [5,2,9,1,7,2,2,3,9]
New_List = []
for item in List:
if item not in New_List:
New_List.append(item)
print(New_List)
Both work fine and The question doesn't say that you can't store the data in another variable as a List, which code is more efficient overall?
Upvotes: 0
Views: 44
Reputation: 22456
Definitely the second one, for multiple reasons:
Therefore, in O notation, you have the following scaling behaviours:
Upvotes: 1