Hi everybody! I don't know if this is possible to do, but here goes:

Hi have a program where I have several lists. Let's call them l1, l2, l3, l4.
Often in the code, I need to delete a certain item from 2 of the lists I have.
I thought about defining a function that only needs to know which lists I want to modify and what item to delete from them.

def myfunction(myl1's_globalname,myl2's_globalname, itemtodelete):
    global myl1's_globalname

The problem is that if I use things like "global myl1's_globalname" when defining the function, I'll have an error saying that global and local variables have the same name.
Isn't there a way to do this such that in the function arguments I write the name of the lists I want to modify and the function makes "global (variable whose name corresponds to 1st argument in the function)"?

thanks in advance!
joana

No need to use global since lists are mutable objects and are passed by reference to a function. Here is an example ...

def remove_item(list1, list2, item):
    """lists are passed by reference so items are removed in place"""    
    if item in list1:
        list1.remove(item)
    if item in list2:
        list2.remove(item)


q1 = ['w', 'a', 'r', 'm']
q2 = ['w', 'a', 't', 'e', 'r', 'y']
q3 = ['l', 'a', 'r', 'g', 'e']
q4 = ['g', 'a', 'r', 'd', 'e', 'n']

print(q1)
print(q2)
remove_item(q1, q2, 'a')
print('-'*10)
print(q1)
print(q2)

"""
my output -->
['w', 'a', 'r', 'm']
['w', 'a', 't', 'e', 'r', 'y']
----------
['w', 'r', 'm']
['w', 't', 'e', 'r', 'y']
"""

Now remember that remove() only removes the first matching item it encounters in each list.

Thanks Vega Seat!
I feel like such a rookie... it's so much simpler than I thought.
Problem solved!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.