-1

i generate a population type class Person. They have 50 elements(self.people) and for this elements i try to create a friendship from this population. In code "for j in self...." i create a new list and remove elements with index j, because person can't be friend itself. When code is running i see that in my list self.people had 25 elements. What is wrong in my code. Thx

def generate_population(self, n, friends_count):
    for i in range(n):
        self.people.append(person.Person(threshold=random.random(), interested_in=random.sample(news.CATEGORIES, 1)))
    for j in self.people:
        fr_list = self.people
        fr_list.remove(j)
        j.make_friends(fr_list, friends_count)


def make_friends(self, population, n):
    fr_list = population
    random_friends = random.sample(fr_list, n)
    for i in random_friends:
        self.friends_list.append(i)
Susan
  • 1
  • 2
  • For debugging help, you need to make a [mre] including complete but minimal code, example input, expected output, and actual output. Also, please write a more descriptive title; see [ask] for tips on that. – wjandrea May 15 '22 at 16:19
  • You can't loop over a list *and* remove elements that you looped over, because then you start skipping elements. See [How to remove items from a list while iterating?](https://stackoverflow.com/q/1207406). That's because list iteration is by index, and deleting elements shifts down all the following elements. What was at index 1 is now index 0, but the loop moves to index 1 and finds the element that was at index 2 before. Etc. – Martijn Pieters May 15 '22 at 16:24

0 Answers0