views:

88

answers:

5

For instance, if I wanted to cycle through a list and perform some operation on all but the final list entry, I could do this:

z = [1,2,3,4,2]
for item in z:
    if item != z[-1]:        
        print z.index(item)

But instead of getting the output "...0 1 2 3," I'd get "...0 2 3."

Is there a way to perform an operation on all but the last item in a list (when there are IDENTICAL items in the list) without using a "for x in range (len(list) - 1)" sort of solution? I.e., I want to keep using "for item in list."

Many thanks!

+1  A: 
for index, item in enumerate(your_list):
    do_something
valya
+3  A: 

you could use:

for index, item in enumerate(z):
    if index != len(z)-1:
        print index
Andre Holzner
or combine it with slicing as proposed in other answers: if you use `enumarate(z[:-1])` instead of `enumerate(z)` you can get rid of the `if` statement.
Andre Holzner
+1  A: 

[z.foo() for z in z[:-1]

leoluk
WOW--you guys are fast. Thanks so much (to all of you)!
Georgina
+8  A: 

Use a slice:

for item in z[:-1]:
    # do something
Peter Milley
+1 This is compact and also easy to understand.
Manoj Govindan
I love python..
daniels
You can reduce the loop overhead of creating a slice by using the `islice` method in the itertools module like this: `for item in itertools.islice(z, 0, len(z)-1):`
martineau
A: 
def all_but_last(iterable):
    iterable= iter(iterable)

    try: previous= iterable.next()
    except StopIteration: return

    for item in iterable:
        yield previous
        previous= item

Put it in a module and use it wherever you need it.

In your case, you'd do:

for item in all_but_last(z):
ΤΖΩΤΖΙΟΥ