Is My Approach to Removing Duplicates in Python Lists Too Inefficient?

0
4
Asked By CuriousCoder92 On

Hi there! I'm currently learning Python and diving into Lists. I came across a problem where I needed to remove duplicates from a list. I know it might be super basic, but I used a method of my own that feels a bit off. I could have gone with a while loop, but instead, I followed this process: 1. I iterate through the list by index, 2. I temporarily remove the current element to avoid comparing it to itself, 3. I mark all other equal elements as duplicates, 4. Reinsert the original element back into the list, and 5. Finally, I delete the marked duplicates.

Here's the code I came up with:

```python
names = ["a", "b", "a", "c", "b"]
for x in range(len(names)):
stripped_for_trial = names.pop(x)
for y in range(len(names)):
if names[y] == stripped_for_trial:
names[y] = "duplicate"
names.insert(x, stripped_for_trial)
```

I noticed one issue—this method relies on a tagging value ("duplicate"). If that tag value appears in the user's list, it could mess things up. What do you think? Am I overthinking this or is this approach just inefficient? Any advice would be appreciated!

3 Answers

Answered By TechSavvy123 On

This approach seems to have a time complexity of O(n^2), since for each element you're iterating through the rest of the list. Generally, O(n^2) isn't seen as efficient, especially for larger lists. You might want to look into Data Structures & Algorithms for a deeper knowledge—there are plenty of courses and books available that can help you understand more efficient methods!

CuriousCoder92 -

Sure, thanks! I'll definitely check it out.

Answered By ListLover42 On

You could also convert the list to a set and then back to a list using `list(set(names))`. This is concise and removes duplicates quickly. However, I get the desire to work through it in pure lists since you're focusing on that now!

TechieTina -

But you won't learn much about algorithms using built-ins!

CuriousCoder92 -

I totally get it! I wanted to explore using just lists to grasp the concept better. Thanks for the tip!

Answered By CodeNinja999 On

A simpler way to handle this is to create a new list and only append items that haven't been added yet, thus avoiding duplicates altogether. It's straightforward and works well!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.