[Tutor] Working with lists
btkuhn at email.unc.edu
btkuhn at email.unc.edu
Sat Dec 13 15:52:44 CET 2008
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?
Thanks.
More information about the Tutor
mailing list