2
my_list = ['ab', 'abc', 'abcd']

for i=0; i<len(my_list); i++

    for j=i+1; j<len(my_list); j++:

        print(my_list[i], my_list[j])

I need two loops like above (in Java or C++) to compare elements with each other. How to do this similarly in Python? I was trying to do this, but it didn't work:

for index, value in enumerate(my_list, start=0):
   for index2, value2 in enumerate(my_list, start=1):
    print(value, value2)

It turns out that the outcome are not the same.

idkman
  • 169
  • 1
  • 15
marlon
  • 99
  • 1
  • 8

3 Answers3

5

You can slice the list using enumerate, but this can be memory intensive depending on the size of the lists.

for index1, value1 in enumerate(my_list):
    for index2, value2 in enumerate(my_list[index1+1:]):
        print(value1, value2)

You can also do the same code similar to the C code.

for i in range(len(my_list)):
    for j in range(i+1, len(my_list)):
        print(my_list[i], my_list[j])
Jmonsky
  • 1,519
  • 1
  • 9
  • 16
4

We could compare each element in the list using combinations in itertools which generates all possible combinations:

import itertools
for a, b in itertools.combinations(mylist, 2):
    compare(a, b)

You could also try the traditional way using your code snippet:

for index1, value1 in enumerate(my_list):
    for index2, value2 in enumerate(my_list[index1+1:]):
        print(value1, value2)
v.coder
  • 1,822
  • 2
  • 15
  • 24
  • It's strange that even if "start=index1+1", value2 still starts at the '0' index. Why is that? – marlon Jul 29 '19 at 18:52
  • If you are interested on getting the indices on ```a``` and ```b``` instead of values directly, you could do also ```for a, b in combinations(range(len(my_list)), 2)``` – Victor Ruiz Jul 29 '19 at 19:18
  • The problem is when we do 'start=1' the values are getting enumerated from 1 to len(my_list)+1. When we print the indices in the second loop it goes from 2 to 4 instead of 1 to 3. Hence we need to either slice before enumerating or use range. – v.coder Jul 29 '19 at 19:24
  • 1
    I am editing my answer with range. – v.coder Jul 29 '19 at 19:25
  • "value2 still starts at the '0' index. Why is that?" Because that's just how `enumerate` is defined. The `start` parameter only changes the number that gets paired up with that index, not the underlying sequence. – Karl Knechtel Jul 30 '19 at 15:38
0

Like this :?

    my_list = ['ab', 'abc', 'abcd']
    for idx in range(len(my_list)):
       for ele in my_list[:idx] + my_list[idx+1:]: 
          print(my_list[idx], ele)
bigeyesung
  • 292
  • 1
  • 3
  • 11