6

So, I notice that calling array[:-1] is going to clone the array.

Say I have a large array with like 3000 elements in it. I don't want it to be cloned as I iterate over it! I just want to iterate to the 2nd last one.

for item in array[ :-1 ] :
  # do something with the item

So do I have to resort to a counter variable,

for c in range( 0, len( array ) - 1 ) :
  # do something with array[ c ]

or is there way to make/will array[:-1] syntax be efficient?

bobobobo
  • 64,917
  • 62
  • 258
  • 363

4 Answers4

6
for item in itertools.islice(array, len(array) - 1):
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
4

Check out itertools.islice:

from itertools import islice
for item in islice(array, 0, len(array) - 1):
    # do something with item

This is about half of what you want; it eliminates the need to say array[i] but not the need to specify len(array) - 1.

For what it's worth, 3000 items is nothing to a modern computer, I wouldn't worry about the inefficiency unless your program is noticeably slow and you've profiled it to determine that this piece of code is a contributing factor.

Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256
2

For when you don't want to/can't/don't know the length of the sequence:

def allbutlast(seq):
  it = iter(seq)
  el = next(it)
  for e in it:
    yield el
    el = e

for i in allbutlast([1, 2, 3]):
  print i
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

I've never used this particular itertools function, but it looks like islice will do what you want

http://docs.python.org/library/itertools.html#itertools.islice

Falmarri
  • 47,727
  • 41
  • 151
  • 191