1

There are two skeleton examples after the function code, called "pets" and "movies"

Need help with my code below because errors keep popping up.

The code:

def cleaner(list1):
    for ele in list1:
        if ele == ['a']['the']['and']:
        print('X')



movies = ["I","watched","a","funny","and","good","movie"]
cleaner(movies)
print(movies)
0

3 Answers 3

2
  1. Your if ele == ['a']['the']['and']: means nothing, how a variable could be equal to 3 lists with ones items each ? (that syntax doesn't even exists

  2. You don't replace anything, you're just printing, your need to change the value inside the list


Here the fix, that modifies inplace the list

def cleaner(list1):
    for i, ele in enumerate(list1):
        if ele in ['a', 'the', 'and']:
            list1[i] = 'X'

pets = ["the", "dog", "and", "a", "cat"]
cleaner(pets)
print(pets)

Here the version that returns a new list, and so require assignement on output

def cleaner(list1):
    blacklist = ['a', 'the', 'and']
    return ['X' if x in blacklist else x for x in list1]

pets = ["the", "dog", "and", "a", "cat"]
pets = cleaner(pets)
print(pets)
Sign up to request clarification or add additional context in comments.

Comments

0
def cleaner(list1):
    for ele in list1:
        if ele == ['a']['the']['and']:
        print('X')

The problem is with your if statement. You have to check each case separately.

if ele=="a" or ele=="the" or ele=="and":

Because what you did there is not a valid Python expression.

1 Comment

posiibly better to use in ele in {"a","the","and"}
0

If you want to modify the contents of a list of immutable objects (strings are immutable in python), you need to do something different than for ele in list. because changing ele will not actually change the contents of the list. (Although, you are not even doing that, you're just printing "X", but I assume that's what you want to do). You can do this instead, which will modify the list in-place:

def cleaner(list1):
    for i in range(len(list1)):
        if list1[i] in ['a', 'the', 'and']:
            list1[i] = 'X'

pets = ["the","dog","and","a","cat"]
cleaner(pets)

Or, an even more elegant approach:


def cleaner(item):
    if item in ['a', 'the', 'and']:
        return 'X'
    else:
        return item


pets = ["the","dog","and","a","cat"]
cleaned_pets = list(map(cleaner, pets))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.