0

I'm new to python but I know other somewhat similar languages quite well, like C#. I am trying to get all pairs for a given array and was wondering why the code at the bottom doesn't output the following:

(7, 2) (7, 3) (7, 9)
(2, 7) (2, 3) (2, 9)
(3, 7) (3, 2) (3, 9)
(9, 7) (9, 2) (9, 3)

Instead the output is:

(7, 2) (7, 3) (7, 9) *Which is correct*
*Skips 2 entirely*
(3, 2) (3, 9) *Doesn't cover (3, 7)*
*Skips 9 entirely*

Any help would be appreciated. Thanks

Code:

weights = [7, 2, 3, 9]

for weight in weights:
    secWeights = weights
    secWeights.remove(weight)
    for sec in secWeights:
        print(weight, sec)
Barmar
  • 741,623
  • 53
  • 500
  • 612
Cian B
  • 31
  • 6
  • 1
    `secWeights` is the same list as `weights` You removed from the list while iterating over it. Don't do that (This is the same in c#) – Pranav Hosangadi Jan 10 '23 at 21:46
  • 2
    `secWeights = weights` doesn't make a copy of the list, the two variables refer to the same list. – Barmar Jan 10 '23 at 21:46
  • 1
    Instead of removing from the list, you could just loop over `weights` in the inner loop, and check `if weight != sec:` – Barmar Jan 10 '23 at 21:49
  • 2
    BTW, you seem to want _permutations_ of `weights`. Python comes with a way to do that. https://docs.python.org/3/library/itertools.html#itertools.permutations – Pranav Hosangadi Jan 10 '23 at 21:50
  • You rarely want to *remove* data in algorithms like this: just *skip* the value you are trying to remove. `for weight in weights: for sec in weights: if weight != sec: print(weight, sec)`. Or as @PranavHosangadi suggests, `for t in itertools.permutations(weights, r=2): print(t)`. – chepner Jan 10 '23 at 21:54
  • The problem with saying if weight != sec is that what if there are two weights with the same value – Cian B Jan 10 '23 at 22:59

1 Answers1

0

You are mutating weights in the first for loop. Try secWeights = weights.copy():

weights = [7, 2, 3, 9]
for weight in weights:
    secWeights = weights.copy()
    secWeights.remove(weight)
    for sec in secWeights:
        print(weight, sec)

dubbbdan
  • 2,650
  • 1
  • 25
  • 43