Python - iterating over lists

238 views Asked by At

I want my code's 2nd function to modify the new list made by my 1st function.

If I am understanding things correctly giving a list as an argument will give the original list (my_list in this case).

so the code removes 1 & 5 and then adds 6, but not 7?

my_list = [1, 2, 3, 4, 5]

def add_item_to_list(ordered_list):
    # Appends new item to end of list which is the (last item + 1)
    ordered_list.append(my_list[-1] + 1)

def remove_items_from_list(ordered_list, items_to_remove):
    # Removes all values, found in items_to_remove list, from my_list
    for items_to_remove in ordered_list:
        ordered_list.remove(items_to_remove)

if __name__ == '__main__':
    print(my_list)
    add_item_to_list(my_list)
    add_item_to_list(my_list)
    add_item_to_list(my_list)
    print(my_list)
    remove_items_from_list(my_list, [1,5,6])
    print(my_list)

output of

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 4, 6, 8]

instead of wanted

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 3, 4, 7, 8]     

Thank you and sorry for the elementary question

4

There are 4 answers

1
Kyle Higginson On

In your remove_items_from_list function you are iterating through the wrong list. You should iterate through every item in the items_to_remove list like this:

def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list

    for item in items_to_remove:
        ordered_list.remove(item) 

This will now iterate through each item in the remove list and remove it from you ordered_list.

1
Evgeny Tanhilevich On

There is a bug in the remove_items_from_list function. For it to achieve what you want it should go:

def remove_items_from_list(ordered_list, items_to_remove):
# Removes all values, found in items_to_remove list, from my_list
    for item in items_to_remove:
        ordered_list.remove(item)

As a side note, your code has incorrect number of blank lines before function definitions. Should be two blank lines before the function, and not more than one blank line inside functions. It seems not to have affected the code for now, but makes it harder to read, and could cause problems in future.

0
pawelty On

In the second function you want to iterate over items_to_remove (and not your original list) and then remove every item.

0
oklen On

Use:

def remove_items_from_list(ordered_list, items_to_remove):
    for item_to_remove in items_to_remove:
        ordered_list.remove(item_to_remove)

And don't change the a list when you are iterating over it,which may cause bug.