5

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)?

Sebastian
  • 2,470
  • 4
  • 21
  • 27

3 Answers3

5

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.

  • 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 Feb 27 '10 at 15:52
1

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

Justin R.
  • 23,435
  • 23
  • 108
  • 157
0

This is how you remove duplicates AND maintain the order (if you care): Algorithm - How to delete duplicate elements in a list efficiently?

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

Community
  • 1
  • 1
Hamish Grubijan
  • 10,562
  • 23
  • 99
  • 147