-2

I would like to have multiple iterators that go over the same list in a for-loop, something like

x = [1,2,3,4]
Triples = []
for i,j,k in range(len(x)):
    print(i,j,k)

Result:

0 0 0
1 1 1
...

Is this possible in python?

My idea is to make the variable i as a reference for j and k.

Jack
  • 105
  • 1
  • 10

2 Answers2

1

Did you mean something like this?

import itertools
x = range(1, 5)
print(x)
print(list(itertools.combinations(x, 3)))
# [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • Yes that is actually the final outcome I would like, but I wanted to try solving this without using the `itertools.combinations` function to help me learn. – Jack Mar 15 '21 at 17:34
  • @Jack, there's search box on the top, [*sometimes*](https://stackoverflow.com/q/20764926/10824407) it's useful. – Olvin Roght Mar 15 '21 at 17:40
  • @OlvinRoght Please explain what a "search box" is, your instructions are unclear. – Jack Mar 15 '21 at 17:44
0

You can try this:

x = [1, 2, 3, 4]

print("elements")
for i, j, k in zip(x, x, x):
    print(i, j, k)

print("\nindexes")
for i, j, k in zip(range(len(x)), range(len(x)), range(len(x))):
    print(i, j, k)

output:

elements
1 1 1
2 2 2
3 3 3
4 4 4

indexes
0 0 0
1 1 1
2 2 2
3 3 3
  • Thank you, this is exactly what I had in mind. Appreciate the answer. Is there any way to achieve this using the same list? – Jack Mar 15 '21 at 17:39