[Tutor] Working with lists

Mark Tolonen metolone+gmane at gmail.com
Sun Dec 14 05:40:44 CET 2008


<btkuhn at email.unc.edu> wrote in message 
news:20081213095244.n4clmwk3k4gkgk04 at webmail4.isis.unc.edu...
> Hi everyone,
>
> I seem to use this pattern alot when writing functions and I'm wondering 
> if there is a more efficient method. It comes up whenever I want to work 
> with more than one item in a list; for instance, say I want to add each 
> consecutive number in alist and output the new list. Ideally, I'd be able 
> to write:
>
> for num in list1:
> newlist.append(num+nextnum)
>
> This doesn't work, though because there's no way to access "nextnum" 
> unless I implement a "count" variable like this:
>
> count=1
> for num in list1:
> newlist.append(num+list1[count])
> count+=1
>
> Instead, it usually ends up easier to write:
>
> for index in range (len(list1)-1):
> newlist.append((list1[index]+list1[index+1]))
>
> It's not a big deal to have to write the additional code, but problems 
> arise when I use this structure in the context of more complex functions, 
> when I am passing multiple lists of varying length, because it is easy to 
> get confused with the index numbers and I can't do anything to the last 
> value of the list, since I then get an "indexerror" because the function 
> tries to call "list[i+1]".
>
> Is there a simpler way to do a procedure like this?

>From your description, do you want:

L = [1,2,3,4,5,6]   result = [3,5,6,9,11]?

I don't see anything in itertools, but this works:

>>> def ishift(L,n):
...         for i in xrange(len(L)-n+1):
...             yield L[i:i+n]
...
>>> for n in shift(L,2):
...         print n
...
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
>>> for a,b,c in shift(L,3):
...         print a,b,c
...
1 2 3
2 3 4
3 4 5
4 5 6
>>> [sum(n) for n in ishift(L,2)]
[3, 5, 7, 9, 11]
>>> [sum(n) for n in ishift(L,3)]
[6, 9, 12, 15]

-Mark




More information about the Tutor mailing list