0

Here is the question:

Implement function processList2(inputList, specialItem, ignoreItems) that returns a new list that contains all the items of inputList (and in the original order) except

  1. Remove any that appear in the list ignoreItems
  2. Occurrences of specialItem (if specialItem is not in ignoreItems) should become the string "special" in the new list.

I am trying to create a new list from inputList using list comprehension. I can get items not in ignoreItems, but can't seem to figure out how to print 'special' if item == specialItem.

Here's what I have so far:

def processList2(inputList, specialItem, ignoreItems):
    return [item for item in inputList if item not in ignoreItems]

a sample output is something like:

>>> processList2([1,1,2,2], 1, [2])
['special', 'special']

or

>>> processList2([1,2,3,4,True,'dog'], 4, [3,5,4])
[1, 2, True, 'dog']
jd2020
  • 9
  • 3
  • Do you want both of them to be printed separately? – Mudits Mar 07 '19 at 19:53
  • 1
    Possible duplicate of [if/else in Python's list comprehension?](https://stackoverflow.com/questions/4260280/if-else-in-pythons-list-comprehension) – mad_ Mar 07 '19 at 19:56
  • No. The output I'm looking for is a list with the items in inputString not in ignoreItems, and the string 'special' if the item in inputList not in ignoreItems is the item in specialItem – jd2020 Mar 07 '19 at 19:57
  • Does it have to be done with a list comprehension? When you have multiple conditions like this, it's much clearer to use a loop with `if/elif/else`. – Barmar Mar 07 '19 at 19:58

1 Answers1

5

You can use the ternary operator in Python.

def processList2(inputList, specialItem, ignoreItems):
    return [item if item != specialItem else "special" for item in inputList if item not in ignoreItems]

See also this post for more on the subject.

Fukiyel
  • 1,166
  • 7
  • 19