1

With pygame I am trying to compare every instance of a class to each other with 2 for loops, but not itself. I am just not clear about how to exclude the first instance. help would be nice

edit: they are stored in a list

nth
  • 93
  • 6

1 Answers1

0

You could use the enumerate function so that, with each instance, you get an index for it in the list. Then, for your second loop, you avoid that index.

enumerate is a built-in function which takes an iterable object and provides you with a running counter in the for loop.

So,

for k, word in enumerate(['alfa','bravo','charlie']):
    print(k, word)

produces

0 alfa
1 bravo
2 charlie
for k, x in enumerate(list_of_instances):
    for y in (_ for j,_ in enumerate(list_of_instances) if j != k):
        do_a_thing()

EDIT:

You could also use slicing for the inner loop. I.e.,

for y in list_of_instances[:k]:
    do_a_thing()
for y in list_of_instances[k:]:
    do_a_thing()
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • i'm still new to python, do u think you can explain this in a little bit more detail? like what do k and x represent in this context? – nth May 19 '20 at 01:50