Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python loop to [:-1]

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?

like image 818
bobobobo Avatar asked Dec 15 '10 21:12

bobobobo


People also ask

What does a [: I mean in Python?

If based on numpy , ans[i,:] means to pick the ith 'row' of ans with all of its 'columns'. Note,when dealing with numpy arrays, we should (almost) always use [i, j] instead of [i][j] . This might be counter-intuitive if you used Python or Java to manipulate matrix before. Follow this answer to receive notifications.

What is Forloop in Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

How do you increment a loop in Python?

To iterate through an iterable in steps, using for loop, you can use range() function. range() function allows to increment the “loop index” in required amount of steps.


3 Answers

for item in itertools.islice(array, len(array) - 1):
like image 78
Josh Lee Avatar answered Oct 03 '22 11:10

Josh Lee


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.

like image 23
Eli Courtwright Avatar answered Oct 03 '22 11:10

Eli Courtwright


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
like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 03 '22 10:10

Ignacio Vazquez-Abrams