Search code examples
pythonlistoperation

Python list operation


I have two lists ListA and ListB as follow:

ListA=['1','1','2','2','2','3','4','4','5','5','5','5']
ListB=['1','5']

I am trying to come up with List C which has the same length as List A but replace the numbers in the List A with 'X' if the number is in the List B.The result i am expecting:

ListC=['X','X','2','2','2','3','4','4','X','X','X','X']

FYI, length of ListB will always less than the length of ListA and ListB will not hold any numbers that is not in List A.

I have tried like this:

ListA=['1','1','2','2','2','3','4','4','5','5','5','5']
ListB=['1','5']
ListC=[]
for items in ListB:
    for a in ListA:
        if items==a:
            ListC.append('X')
        else:
            ListC.append(a)

obviously this will create a List that has (length of listB X lenght A) rather than just just the length of list A. Is there any built in function that does this operation? Could anyone give me a clue how to do it?


Solution

  • You can use a list comprehension:

    [i if i not in ListB else 'X' for i in ListA]
    

    To fix your current code, use in to check to see if the item is in ListB:

    for item in ListA:
        if item in ListB:
            ListC.append('X')
        else:
            ListC.append(item)