suggestions for improving code fragment please

Terry Reedy tjreedy at udel.edu
Thu Feb 28 22:30:36 CET 2013


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




More information about the Python-list mailing list