Re: suggestions for improving code fragment please

Discussion in 'Python' started by Terry Reedy, Feb 28, 2013.

  1. Terry Reedy

    Terry Reedy Guest

    On 2/28/2013 2:47 PM, The Night Tripper wrote:
    > Hi there
    > I'm being very dumb ... how can I simplify this fragment?
    >
    >
    > if arglist:
    > arglist.pop(0)
    > if arglist:
    > self.myparm1 = arglist.pop(0)
    > if arglist:
    > self.myparm2 = arglist.pop(0)
    > if arglist:
    > self.myparm3 = arglist.pop(0)
    > if arglist:
    > self.parm4 = arglist.pop(0)


    To literally do the same thing

    try:
    arglist.pop(0)
    self.myparm1 = arglist.pop(0)
    self.myparm2 = arglist.pop(0)
    self.myparm3 = arglist.pop(0)
    self.parm4 = arglist.pop(0)
    except IndexError:
    pass

    However, repeated popping from the front is O(n**2) instead of O(n).
    Following should do the same, including removal from original arglist.

    it = iter(arglist)
    n = 0
    try:
    next(it); n += 1
    self.myparm1 = next(it); n += 1
    self.myparm2 = next(it); n += 1
    self.myparm3 = next(it); n += 1
    self.parm4 = next(it); n += 1
    except StopIteration:
    pass
    arglist = arglist[n:]

    --
    Terry Jan Reedy
    Terry Reedy, Feb 28, 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. Rick Johnson
    Replies:
    0
    Views:
    95
    Rick Johnson
    Feb 28, 2013
  2. Joel Goldstick
    Replies:
    0
    Views:
    102
    Joel Goldstick
    Feb 28, 2013
  3. Ian Kelly
    Replies:
    0
    Views:
    93
    Ian Kelly
    Feb 28, 2013
  4. Tim Chase
    Replies:
    0
    Views:
    95
    Tim Chase
    Feb 28, 2013
  5. MRAB
    Replies:
    0
    Views:
    91
Loading...

Share This Page