Re: Retrieving an object from a set

Discussion in 'Python' started by Ian Kelly, Jan 25, 2013.

  1. Ian Kelly

    Ian Kelly Guest

    On Fri, Jan 25, 2013 at 4:30 PM, Ian Kelly <> wrote:
    > On Fri, Jan 25, 2013 at 4:14 PM, Arnaud Delobelle <> wrote:
    >> Dear Pythoneers,
    >>
    >> I've got a seemingly simple problem, but for which I cannot find a
    >> simple solution.
    >>
    >> I have a set of objects (say S) containing an object which is equal to
    >> a given object (say x). So
    >>
    >> x in S
    >>
    >> is true. So there is an object y in S which is equal to x. My
    >> problem is how to retrieve y, without going through the whole set.

    >
    > You could use a dict.
    >
    >>>> y = (1, 2, 3)
    >>>> S = {x: x for x in [y] + range(10000)}
    >>>> x = (1, 2, 3)
    >>>> x in S

    > True
    >>>> x is y

    > False
    >>>> S[x] is y

    > True


    Or you could use a set intersection:

    >>> S = set([y] + list(range(10000)))
    >>> S.intersection([x]).pop()

    (1, 2, 3)

    In my testing, the time needed for this is small and does not seem to
    depend on the size of the set.
    Ian Kelly, Jan 25, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Arnaud Delobelle

    Retrieving an object from a set

    Arnaud Delobelle, Jan 25, 2013, in forum: Python
    Replies:
    1
    Views:
    112
    Steven D'Aprano
    Jan 26, 2013
  2. Ian Kelly

    Re: Retrieving an object from a set

    Ian Kelly, Jan 25, 2013, in forum: Python
    Replies:
    0
    Views:
    110
    Ian Kelly
    Jan 25, 2013
  3. MRAB
    Replies:
    0
    Views:
    109
  4. Ethan Furman

    Re: Retrieving an object from a set

    Ethan Furman, Jan 25, 2013, in forum: Python
    Replies:
    0
    Views:
    109
    Ethan Furman
    Jan 25, 2013
  5. Dave Angel

    Re: Retrieving an object from a set

    Dave Angel, Jan 25, 2013, in forum: Python
    Replies:
    0
    Views:
    113
    Dave Angel
    Jan 25, 2013
Loading...

Share This Page