Does a list translate into a set, and then back, cause problems in Python?

I turn the list into a collection in Python, for example:

request.session['vote_set'] = set(request.session['vote_set'])

Therefore, I can easily search if x in setand eliminate duplicates. Then, when I am done, I will convert it:

request.session['vote_set'] = list(request.session['vote_set'])

Is there a better way to do this? Can I do something dangerous (or stupid)?

+5
source share
3 answers

You will lose duplicates if you want. If this is actually a list of "votes", as your name says, you would have "lost" :)

why not just:

if x in set(request.session['vote_set'])

if you are worried.

Although I need to wonder if this will be slower than simple:

if x in request.session['vote_set']

And the order, as others have pointed out, will potentially (most likely) be lost.

+5
source

, .

+1

So you remove duplicates and maintain order (if you're interested): Algorithm - How to efficiently remove duplicate items in a list?

Other answers showed how to turn a list into a set.

0
source

All Articles