tags:

views:

96

answers:

3

I'm turning a list into a set in Python, like so:

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

So I can easily do a if x in set lookup and eliminate duplicates. Then, when I'm done, I reconvert it:

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

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

+1  A: 

You'll lose ordering, if that's important to you.

fatcat1111
+3  A: 

You'll lose duplicates if you actually wanted them. If this is actually a list of "votes" as your naming suggests, you'd 'lose' some :)

why not just:

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

if you're worried.

Although I have to wonder if that would be slower than just plain:

if x in request.session['vote_set']

And ordering, as others have mentioned, would potentially (most likely) be lost.

Chris Cameron
Converting to a set (which involves traversing the whole list once) just to test membership once will be slower than testing for membership in the list (which involves traversing the list until a match is found). If the set is large and you can use it more than once, at some point it will become faster; that's not likely to be the case here though.
Peter Hansen
A: 

This is how you remove duplicates AND maintain the order (if you care): http://stackoverflow.com/questions/1801459/algorithm-how-to-delete-duplicate-elements-in-a-list-efficiently

The other answers showed how to turn a list into a set.

Hamish Grubijan