1

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

Mark D. Foti
  • 59
  • 1
  • 7

3 Answers3

2

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.

Shubham Gupta
  • 1,917
  • 1
  • 10
  • 16
  • If you are counting duplicates in a list, I would suggest you use Counter or HashMap which will reduce your time complexity to O(n). You can check out this [link](https://stackoverflow.com/questions/23240969/python-count-repeated-elements-in-the-list/23240989) – Shubham Gupta May 15 '20 at 03:38
1

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")
Mark
  • 90,562
  • 7
  • 108
  • 148
1

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

João Castilho
  • 487
  • 4
  • 19