DEV Community

Discussion on: 5 Python Tricks in one line. Beginner vs Professional

Collapse
 
kbauer profile image
kbauer

There are errors in the part about removing duplicates.

  1. fruits = { ... } already is a set, and so the duplicates are already discarded before reaching the loop.

  2. The output of

    new = set(fruits)
    

    is not

    ['banana', 'apple', 'pear', 'orange']
    

    but (order may differ)

    {'banana', 'apple', 'pear', 'orange'}
    

    The output you show would be obtained by

    new = list(set(fruits))
    

Overall, to be correct, the example would have to be changed to

# List instead of set
fruits = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

# Actually make `new` a list
new = list(set(fruits))
Enter fullscreen mode Exit fullscreen mode

Additionally, for a beginner post it would be very useful to point out that, in addition to be more concise,

new = list(set(fruits))
Enter fullscreen mode Exit fullscreen mode

has O(N) time complexity[1], while

for fruit in fruits:
    if fruit not in new:
        new.append(fruit)
Enter fullscreen mode Exit fullscreen mode

has O(N²) time complexity.

[1] In CPython anyway, which should be using a hash-table based set implementation. Note sure though, whether the loop or the set based solution is faster for small numbers of elements.

Collapse
 
vadimkolobanov profile image
Vadim Kolobanov

Thank you so much for the addition. Initially, my goal was just to show the difference in solutions to some problems. I will definitely add your suggestion about algorithmic complexity! And you also gave me the idea to write an article about calculating algorithmic complexity

Collapse
 
ruudvanderham profile image
ruudvanderham

Under Python 3.6 and higher this one liner will also maintain the order
new = list(dict.fromkeys(fruits))
and it is O(n)!

Collapse
 
vadimkolobanov profile image
Vadim Kolobanov

Thank you all so much) You really help all readers to become a little more literate

Collapse
 
kbauer profile image
kbauer

Interesting to know, but hard to read :/ If I'd see this in the code I wouldn't be aware, that preserving the order is an intent here.

Thread Thread
 
ruudvanderham profile image
ruudvanderham

Just adding a comment would help.

Thread Thread
 
vadimkolobanov profile image
Vadim Kolobanov

Guys, I pointed out your help in the article and asked you to pay attention to the comments) So thank you very much! Many opinions, and various practices make this article even better)