1

I have been coding in C++ and Java for some time. I have started to code in Python recently as well. However, I got stuck in the case of nested for loops in Python. I have written following code in C++. What will be the equivalent code of it in Python?

for(int i = 0; i<a.size();i++){
   for(int j = i; j<a.size();j++)
   {
       if a[i] != a[j]
          /*some code */
   }

}

I tried to use enumerate as follows, but it fails:

for i, val in enumerate(lst):
    for j=i,val2 in enumerate(lst):
        if val != val2
            #some code

So how can I represent the C++ nested loops in python?

3 Answers 3

4
import itertools

for val1, val2 in itertools.combinations(lst, 2):
    if val1 != val2:

combinations will loop over all cases of choosing two distinct elements from your list which is what your nested for loops are doing anyhow. Note that your second nested for loop is initialized at j=i, but that first case will always fail to process anyhow because it will never pass the conditional.

If you really, really need the indices, and usually you shouldn't, you can do:

for (i, val1), (j, val2) in itertools.combinations(enumerate(lst), 2):
    if val1 != val2:
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the comment. What if my condition in the second for loop is j = i + 1. How will itertools work in that case?
That was my point, whether you do j = i or j = i+1 is the same because of the subsequent conditional. Without the subsequent conditional, the python loop code is like j = i + 1 because combinations will not take the same element twice. If you wanted to do j =i without the conditional in python it's a different situation and my answer would be different.
1

As mentioned elsewhere, enumerate does one thing (provide indexes). It will not truncate or skip around in your list. If you wanted to use enumerate, one option is to pass a list slice instead of the full list, and use the start= keyword argument to start the index numbering correctly:

for i, val in enumerate(lst):
    for j, val2 in enumerate(lst[i:], start=i):
        if val != val2:
            #some code

Comments

1

The enumerate function doesn't have a start index, however range does in that sense. It should be noted that while enumerate(sequence, start=0) has a start parameter, it only specifies the start of the returned index, and not the first index of which the list is accessed.

So you could do it like this:

n = len(lst)
for i in range(n):
    val = lst[i]
    for j in range(i, n):
        val2 = lst[j]
        if val != val2:
            #some code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.