[Tutor] working with empty lists
Joel Goldstick
joel.goldstick at gmail.com
Thu Sep 16 18:21:23 CEST 2010
On Thu, Sep 16, 2010 at 11:46 AM, Rance Hall <ranceh at gmail.com> wrote:
> On Thu, Sep 16, 2010 at 9:24 AM, Joel Goldstick
> <joel.goldstick at gmail.com> wrote:
> > I typed in this:
> >
> >
> > 3 l = []
> > 4
> > 5 for i in range(0,10):
> > 6 l.append(i+1)
> > 7
> > 8 for i in range(0,10):
> > 9 print ('%s. %s' % (i, l[i]))
> > 10
> > 11 def paginate_stuff(list, start):
> > 12 pagesize = 2
> > 13 for i in list[start:start+pagesize]:
> > 14 print ('%s. %s' % (i,list[i]))
> > 15 return
> > 16
> > 17 paginate_stuff(l,0)
> >
> > and i get this:
> > 0. 1
> > 1. 2
> > 2. 3
> > 3. 4
> > 4. 5
> > 5. 6
> > 6. 7
> > 7. 8
> > 8. 9
> > 9. 10
> > 1. 2
> > 2. 3
> >
> >
> > What are you expecting?
> >
> >
>
> you are getting what I am getting, so good news there, its not my code
> (its my understanding instead)
>
> In the above output where the you go from 9. 10 and the next item is 1. 2
>
> I'm expecting the next item to be 0. 1 again.
>
> It appears as if the for loop iterator is iterating BEFORE it executes
> stuff as opposed to after like I'm used to.
>
> if I change the print line inside the for loop to:
>
> print('%s. %s) % (i-1,list[i-1]))
>
> I get what I think I should have gotten orginally
>
> Is this the correct understanding, is the for loop iterator iterating
> before any of the stuff executes the first time? This seems odd to me
> somehow.
>
> I appear to have fixed it, now I just wish I understood it.
>
> R
>
This line is illustrative:
> 13 for i in list[start:start+pagesize]:
start is 0, pagesize is 2 so we get list[0:2] which means i gets the value
of what is in list[0], then next time list[1] then it stops
list[0] IS 1, list[1] is 2
so: > 14 print ('%s. %s' % (i,list[i]))
will print 1. list[1] which is 2
then print 2. list[2] which is 3
maybe what you want is this:
for i, value enumerate(list[start:start+pagesize], start):
print i, value
_______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
--
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/ad15db3f/attachment.html>
More information about the Tutor
mailing list