[Tutor] Possible usage of dict comprehensions

Alan Gauld alan.gauld at yahoo.co.uk
Mon Oct 19 19:42:36 EDT 2020


On 20/10/2020 00:19, Manprit Singh wrote:
> is maintained. If I want to remove duplicates from a list while maintaining
> the order of its elements, doing like this is a valid and a useful use case

>>>> l = [2, 4, 5, 3, 4, 5, 2, 1]   # List whose duplicates have to be
> removed
>>>> list({i:None for i in l})
> [2, 4, 5, 3, 1]                   # Resultant list with duplicates removed
> , order preserved

Well you have demonstrated that it works so it must be valid.
How useful it is depends on whether you need to perform that operation.
Assuming you do then yes its useful.

It's probably fairly efficient too but I haven't timed it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list