0

I want to build a nested for loop. I have a list and from that list I want to create a new list with special conditions. The resulting list is my list_copy. Here is my code:

list = [['20973973', 3, ['4833718', '23420317', '25763872']],
['21105775', 3, ['4064497', '254324813', '386991470']],
['21112149', 3, ['4006412', '303889818', '303923833']]]

list_copy = list

for i in range(len(list)):
    for j in range(len(list[i][2])):
        path = './way[@id="' + str(list[i][2][j]) + '"]'
        way_elem = tree.find(path)
        for tag in way_elem.iter('tag'):
            if tag.get('k') == 'highway':
                if tag.get('v') == "motorway_link" or tag.get('v') == "motorway_junction":
                    if list[i] in list_copy:
                        list_copy.remove(list[i])

With these code I get the error:

    for j in range(len(list[i][2])):
IndexError: list index out of range I am really trying long on these and it seems that this 

So I understand that the error occurs in the second for loop with the index i=2. But I don't know why because the len(list) is 3, so list[2][2] should be no index out of range.

Lena
  • 31
  • 4
  • 2
    When you do `list_copy = list` and then `list_copy.remove(list[i])`, it's affecting `list` still. – Random Davis Dec 01 '20 at 16:05
  • 2
    Thank you @RandomDavis. That's true... I will create a full new list with append-Commands and reverse the conditions, thank you so much! And sorry for the silly question.. – Lena Dec 01 '20 at 16:08
  • Yes, thank you, @MauriceMeyer – Lena Dec 01 '20 at 16:08

1 Answers1

0
  • Change the name of the list from list to something else like lst.

  • Create a shallow copy of the list.

list_copy  = list(lst)
Shadowcoder
  • 962
  • 1
  • 6
  • 18