0

I was recently solving some questions on hacker rank when I came across a question where we had a list of lists and we have to remove the list whose sum of elements is 2(in my case). Input was 1 1 1 2 and the original list generated was [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]] so according to the my code the sub lists of [0, 1, 1],[1, 0, 1], [1, 1, 0] should be removed but the output I was getting is [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1]] . Can someone please explain why the sub list of [1, 1, 0] is still present. Here is the code:

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    
    lists = []
    for i in range(x+1):
        for j in range(y+1):
            for k in range(z+1):
                lists.append([int(i), int(j), int(k)])   
    print(lists)  

    for list in lists:
        value = list[0] + list[1] + list[2]
        if value == n:
            print(list)
            lists.remove(list)           

    print(lists)

Here is the Output that I am getting

  • Provide the output in formatted text, not in an image. All information core to the question should be included in formatted text and not images or external links. Also, don't tag the question as both Python 2 and 3. They're two distinct languages. Tag only the version you're using. – Ted Klein Bergman Feb 09 '21 at 18:15
  • 2
    typical remove while iterating problem. https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating – Dyno Fu Feb 09 '21 at 18:16
  • 1
    Also it's good practice to avoid using reserved keywords like `list` as a variable name. – pault Feb 09 '21 at 18:18

0 Answers0