Loop through Python list with 2 variables
I assume that you want a solution that can do anything with the indices, not just print them out. Python's for
loops have other strengths. So use a while
loop.
i = 0
j = len(alist)
while i < j:
print(i, j) # or console.log(i, j) or whatever you want here
i += 1
j -= 1
Here is something similar using zip
, which is more pythonic. Here I illustrate doing something other than just printing the indices.
alist = [3, 1, 4, 1, 5, 9]
llen = len(alist)
for i, j in zip(range(llen // 2), range(llen - 1, -1, -1)):
print(alist[i], alist[j])
But it is even more pythonic to ignore the indices and just use the items of the list, as in
alist = [3, 1, 4, 1, 5, 9]
llen = len(alist)
for u, v in zip(alist[:llen // 2], alist[::-1]):
print(u, v)
Here's an example how you can do it. Take second index as function of length minus index minus one:
l = [1, 2, 3, 4]
for i, _ in enumerate(l):
print(l[i], l[len(l)-i-1])
This will output
(1, 4)
(2, 3)
(3, 2)
(4, 1)
Not printing indexes themselves, but you can print them, if you chose to do so.