OfirEl
OfirEl

Reputation: 3

Which of these 2 codes is more efficient?

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.

  1. My code:
List = [5,2,9,1,7,2,2,3,9]
for item in List:
    while(List.count(item) >= 2):
        List.remove(item)
print(List)
  1. Second code:
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

Answers (1)

Finomnis
Finomnis

Reputation: 22456

Definitely the second one, for multiple reasons:

  • The first one should never be used. It isn't safe to iterate through a list and delete items at the same time.
  • Deleting an item from a list is an O(n) heavy task, because you always need to copy half the list.

Therefore, in O notation, you have the following scaling behaviours:

  • first: Computation: O(n^2); Space: O(n), to be exact 2*n
  • second: Computation: O(n), Space: O(n), to be exact 3*n

Upvotes: 1

Related Questions