I want to know if there's a more Pythonic way of doing the following:
A = some list
i = 0
j = 1
for _ in range(1, len(A)):
#some operation between A[i] and A[j]
i += 1
j += 1
I feel like this should/could be done differently. Ideas?
EDIT: Since some are asking for requirements. I wanted a general-purpose answer. Maybe to check if A[i], A[j] are between a certain range, or if they're equal. Or maybe I wanted to do a "trickle-up" of elements. The more general, the better.
There's a nice little recipe in itertools
for doing this. As a bonus it works with any iterable, not just sequences.
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for current, next_ in pairwise(A):
# do something
pass
If you need the index as well then just enumerate
the pairwise iterator.
for current_index, (current, next_) in enumerate(pairwise(A)):
# do something
pass
zip
lets you combine multiple iterators:
for i,j in zip(range(0,len(A)-1), range(1,len(A))):
#some operation between A[i] and A[j]
you can also use enumerate
on a range object:
for i,j in enumerate(range(1,len(A)):
#some operation between A[i] and A[j]
Note that unlike the other answers this gives you access to the indices of A not just the items, this is necessary if you want to use any assignment to A[i]
or A[j]
, for example here is a very basic bubble sort:
A = list(range(10))
found1=True
while found1:
found1=False
for i,j in enumerate(range(1,len(A))):
if A[i] < A[j]:
A[i],A[j] = A[j],A[i]
found1=True
print(A)
this is only possible when you iterate over the indices of A.
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