no shift/unshift?

sismex01 at hebmex.com sismex01 at hebmex.com
Fri Feb 21 15:31:17 EST 2003


> From: Michael P. Soulier [mailto:msoulier at storm.ca._nospam]
> Sent: Friday, February 21, 2003 2:18 PM
> 
>     Hello,
> 
>     I was wondering, is there no built-in way to pull values 
> off and on to a list in python? append and pop are find if
> you are working with the right side, but if you need to work
> with both, having something like shift and unshift from perl
> would be nice. 
>     If I just need to simulate a stack, I'll reverse the list 
> if need be, but sometimes I want to manipulate both sides. 
> 
>     For consistency, it'd be nice to see append called push, 
> too. append and pop just sounds wrong when thinking about a
> stack. :)
> 
>     Thanks for any advice,
>     Mike
>

It's perfectly doable, but this is not Perl, it's Python,
so it has it's own method names.  Or, you can subclass
list so that it conforms:

class PerlyList(list):
    def unshift(self, *args):
        if args: self[:0] = list(args)
        return self
    def shift(self):
        return self.pop(0)
    def push(self, *args):
        if args: self.extend(list(args))
        return self

And it also returns self on apropriate methods,
so you can chain them together.

ewww...  I'm gonna regret this.

-gus






More information about the Python-list mailing list