Skip to content Skip to sidebar Skip to footer

Python: If Element In One List, Change Element In Other?

I have two lists (of different lengths). One changes throughout the program (list1), the other (longer) doesn't (list2). Basically I have a function that is supposed to compare the

Solution 1:

Try this:

newlist = ['A' if x in list1 else 'B' for x in list2]

Works for the following example, I hope I understood you correctly? If a value in B exists in A, insert 'A' otherwise insert 'B' into a new list?

>>> a = [1,2,3,4,5]
>>> b = [1,3,4,6]
>>> ['A'if x in a else'B'for x in b]
['A', 'A', 'A', 'B']

Solution 2:

It could be because instead of

newList: list2[:]

you should have

newList = list2[:]

Personally, I prefer the following syntax, which I find to be more explicit:

importcopy
newList = copy.copy(list2) # or copy.deepcopy

Now, I'd imagine part of the problem here is also that you use the same name, newList, for both your function and a local variable. That's not so good.

def newList(changing_list, static_list):
    temporary_list = static_list[:]
    for index, content in enumerate(temporary_list):
        if content in changing_list:
            temporary_list[index] ='A'else:
            temporary_list[index] = 'B'return temporary_list

Note here that you have not made it clear what to do when there are multiple entries in list1 and list2 that match. My code marks all of the matching ones 'A'. Example:

>>> a = [1, 2, 3]
>>> b = [3,4,7,2,6,8,9,1]
>>> newList(a,b)
['A', 'B', 'B', 'A', 'B', 'B', 'B', 'A']

Solution 3:

I think this is what you want to do and can put newLis = list2[:] instead of the below but prefer to use list in these cases:

def newList1(list1,list2):         
     newLis =list(list2)
     for i in range(len(list2)):  
          if newLis[i] in list1:  
               newLis[i]='A'else: newLis[i]='B'return newLis

The answer when passed

newList1(range(5),range(10))

is:

['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B']

Post a Comment for "Python: If Element In One List, Change Element In Other?"