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?
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.
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.
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.
for item in itertools.islice(array, len(array) - 1):
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With