2

I have a list: fruits = ['apple', 'orange', 'blueberry', strawberry']

How do I create loops such that one index depends on another:

for i in range(len(fruits)):
   for j range(len(fruits[i+1:])):
       print i,j

I want to print out the pairs:

'apple', 'orange'
'orange', 'blueberry'
'blueberry', strawberry'
'orange', 'blueberry'
etc...

I would like to obtain loops that correspond to the c++ language:

 for(i=0;i<5;i++) 
     for (j=i+1; j<5; j++)
         print i, j
smac89
  • 39,374
  • 15
  • 132
  • 179
Monica
  • 1,030
  • 3
  • 17
  • 37
  • Your outputs don't make any sense given your inputs. Do you want to make pairs of adjacent elements, or pair each fruit with every other fruit? The former would be done with `zip` (see [the `itertools` recipe for `pairwise`](https://docs.python.org/3/library/itertools.html#itertools-recipes)), the latter [with `itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations). – ShadowRanger Feb 10 '17 at 03:10
  • 2
    Why do you need two loops for this? I might have misunderstood what you want but to get the output you have shown you can just do `for i in range(1, len(fruits)): print fruits[i-1], fruits[i]` – Munir Feb 10 '17 at 03:14

4 Answers4

4

If you want what the C++ code prints out, use itertools.combinations:

In [1]: import itertools

In [3]: fruits = ['apple', 'orange', 'blueberry', 'strawberry']

In [4]: for res in itertools.combinations(fruits, 2):
   ...:     print res
   ...:
('apple', 'orange')
('apple', 'blueberry')
('apple', 'strawberry')
('orange', 'blueberry')
('orange', 'strawberry')
('blueberry', 'strawberry')
cizixs
  • 12,931
  • 6
  • 48
  • 60
1

Based on your output, I am going with this

fruits = ['apple', 'orange', 'blueberry', 'strawberry']
l = len(fruits)

for i in range(l):
   for j in range(i, l - 1):
       print fruits[j], fruits[j + 1]

Output:

apple orange
orange blueberry
blueberry strawberry
orange blueberry
blueberry strawberry
blueberry strawberry
smac89
  • 39,374
  • 15
  • 132
  • 179
0
for i in range(len(fruits)-1):
   print fruits[i], fruits[i+1]
Phrogz
  • 296,393
  • 112
  • 651
  • 745
0

If I understand correctly, try:

>>> fruits = ['apple', 'orange', 'blueberry', 'strawberry']
>>> from itertools import combinations
>>> list(combinations(fruits,2))
[('apple', 'orange'), ('apple', 'blueberry'), ('apple', 'strawberry'), ('orange', 'blueberry'), ('orange', 'strawberry'), ('blueberry', 'strawberry')]

Or, just Pythonize your C loops:

>>> for i in range(0, len(fruits)):
...     for j in range(i+1, len(fruits)):
...        print fruits[i], fruits[j]
... 
apple orange
apple blueberry
apple strawberry
orange blueberry
orange strawberry
blueberry strawberry
dawg
  • 98,345
  • 23
  • 131
  • 206