0

I managed to solve my problem, but I don't understand the problem itself. Yeah, I've been lucky enough to fix it, but it won't be as useful if I don't understand why I had this problem.

When running a for loop inside an object's function, this loop was always skipping one value of the list, just like if the for loop step was set to 2.

Below is a very very simplified and adapted version of my first code, but it gives a good idea of how it works.

class Food:
    def __init__(self, my_list):
        self.my_list = my_list

    def food_iterator(self):
        while True:
            for element in self.my_list:
                print(element)

Food(['pasta', 'chicken', 'porc', 'cheese', 'lasagna']).food_iterator()

When creating a copy of the original list:

class Food:
    def __init__(self, my_list):
        self.my_list = my_list

    def food_iterator(self):
        my_list_copy = [m for m in self.my_list])

        while True:
            for element in my_list_copy:
                print(element)

Food(['pasta', 'chicken', 'porc', 'cheese', 'lasagna']).food_iterator()

it just worked perfectly. But I don't understand why it wasn't working before and why it is now...

I would really appreciate to hear your thoughts!

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 1
    The problem you describe happens when you are deleting elements from a list you're iterating over - it doesn't happen when just printing the elements, but the code you posted won't actually run due to indentation problems, so I have no idea what your actual code is. – jasonharper Aug 19 '20 at 16:05
  • I couldn't reproduce the issue. Just two sidenotes: [don't use mutable default arguments](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument), and a better iterator would be `yield from self.my_list`. – Péter Leéh Aug 19 '20 at 16:08
  • It's worth pointing out that you have "while True" in the code but there's no "break", so your code will run endlessly. See more [here](https://stackoverflow.com/questions/3754620/what-does-while-true-mean-in-python). – Heron Yang Aug 20 '20 at 04:53
  • Thank you very much for your answers, I think that mutable default arguments are the source of my problem. I will take a closer look at this and learn to fix it – PythonTrade Aug 20 '20 at 08:30

0 Answers0