Mark D. Foti
Mark D. Foti

Reputation: 59

Nested For Loop Counter

I am very beginner with Python and am having trouble with a certain aspect of the counter as it relates to its use in a nested for loop.

I am trying to run a nested for loop that checks if an array A has any duplicate values.

Trying to talk myself (and y'all) through this to make sense out of it: I am using a nested for loop to essentially loop through each item in array A...and for each item in array A, I need another counter to loop A so that I can compare A to itself in the form of counter i and counter j. Here is the issue: I don't want to count on itself aka i don't want to double count. And if I simply type the code that y'all will see below, it will double count (count on itself). So I want to make sure that the index of my inner for loop's counter is always +1 to my outer for loops counter.

Here is what the code looks like:

A = [4, 3, 2, 4]

for i in A:
    for j in A:
        if i == j:
            print("yup")

the output is...you guessed it:

yup
yup
yup
yup
yup
yup

6 "yup"'s because each time it is counting each number on itself.

Hopefully I am explaining that properly...

So my question is: does anybody know how to make sure that my "j" counter is indexed +1...

I thought it would be:

for i in A:
    for j = i + 1 in A:
        if i == j:
            print("yup")

but apparently that isn't right

Any insight here is very much appreciated!!!

Thanks, Mark

Upvotes: 1

Views: 1296

Answers (3)

Mark
Mark

Reputation: 92461

You can use enumerate to get the current index in the outside loop and then loop over a slice on the inside:

A = [4, 3, 2, 4]

for i, n_outer in enumerate(A):
    for n_inner in A[i+1:]:
        if n_inner == n_outer:
            print("yup")

Upvotes: 1

João Castilho
João Castilho

Reputation: 487

This is a solution for your problem. enumerate function returns a tuple with the index and value of each array element.

for idx_i, elem_i in enumerate(A):
  for idx_j, elem_j in enumerate(A[idx_i+1:]):
      if elem_i == elem_j:
         print("Yup")

If you want an array with unique elements, there are better efficient ways to do that

Upvotes: 1

Shubham Gupta
Shubham Gupta

Reputation: 2007

If you want to start j from 1 you can simply use the range function

for i in range(len(A)):
    for j in range(i+1,len(A)):
        if A[i] == A[j]:
            print("yup")

Hope this is what you are looking for.

Upvotes: 2

Related Questions