0

How do you compare the objects in two lists, and then if there are two of the same objects in both lists, replace it with something? For example:

list1 = [a,b,c,d]
list2 = ['h','j','a','d']

I want to say, if some of the objects in list1 are the same with some of the objects in list2, replace those objects with something else (For example, 'hello')

MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 1
    Possible duplicate of [Common elements between two lists not using sets in Python](https://stackoverflow.com/questions/2727650/common-elements-between-two-lists-not-using-sets-in-python) – Sanandrea Aug 01 '17 at 17:36

2 Answers2

1
list1 = [x if x not in list2 else 'hello' for x in list1]
user257297
  • 46
  • 2
1

Try using a list comprehension and the ternary operator.

liam
  • 1,918
  • 3
  • 22
  • 28