[Tutor] inserting items into a list

Julieta Rangel julieta_rangel@hotmail.com
Fri, 04 May 2001 19:14:22 -0500


Daniel,

Great suggestion!  Everyday I learn something new about programming.  I had 
no idea I could do it.  I only thought about it because it would be easy for 
me not having to combine like terms in the multiplication of polynomials.  I 
knew that if I did it this way I would not have to combine like terms, which 
would take me at least a day to figure out how to do it [you know what a 
slow poke I am at this :)].


>From: Daniel Yoo <dyoo@hkn.eecs.berkeley.edu>
>To: Julieta Rangel <julieta_rangel@hotmail.com>
>CC: tutor@python.org
>Subject: Re: [Tutor] inserting items into a list
>Date: Thu, 3 May 2001 22:41:33 -0700 (PDT)
>
>On Thu, 3 May 2001, Julieta Rangel wrote:
>
> > [3,0,6], then [1,0,2] and finally [2,0,4].  I need to find a way to 
>insert 3
> > zeroes at the end of list [2,0,4]; 1 zero at the beginning and two at 
>the
> > end of [3,0,6]; 2 zeroes a the beginning and one at the end of [1,0,2], 
>and
> > finally 3 zeroes at the beginning of [2,0,4].  This way the new lists 
>would
> > look like:
> >
> > [2,0,4,0,0,0]
> > [0,3,0,6,0,0]
> > [0,0,1,0,2,0]
> > [0,0,0,2,0,4]
> >
> > and it would be just a matter of adding those lists to figure out the
> > result:  2 + 3x + 5x^2 + 8x^3 + 2x^4 + 4x^5.  As you can see from the
> > subject, my problem is inserting those zeroes at the specific locations.
> > Can you help me?
>
>
>How about something like this?
>
>###
>def makeZeroPaddedList(mylist, position, length):
>     """This function should take mylist, and splice it into
>        a list of zeros at a specific location."""
>     newlist = [0] * length
>     newlist[position:position + len(mylist)] = mylist
>     return newlist
>###
>
>
>Let's test it out on the interpreter:
>
>###
> >>> makeZeroPaddedList([1, 2, 3], 0, 10)
>[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]
> >>> makeZeroPaddedList([1, 2, 3], 1, 10)
>[0, 1, 2, 3, 0, 0, 0, 0, 0, 0]
> >>> makeZeroPaddedList([1, 2, 3], 2, 10)
>[0, 0, 1, 2, 3, 0, 0, 0, 0, 0]
> >>> makeZeroPaddedList([1, 2, 3], 3, 10)
>[0, 0, 0, 1, 2, 3, 0, 0, 0, 0]
> >>> makeZeroPaddedList([1, 2, 3], 4, 10)
>[0, 0, 0, 0, 1, 2, 3, 0, 0, 0]
>###
>
>
>The idea is to make up a list that's filled only with zeros, and then plop
>our original list into it.  We can control both the position of the
>plopping, and the length of the resulting list.
>
>Hope this helps!
>

_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com