randomdude788
randomdude788

Reputation: 11

Modifying functions of lists and replacing strings in python

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)

Upvotes: 1

Views: 43

Answers (3)

ahmadPH
ahmadPH

Reputation: 149

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))

Upvotes: 0

azro
azro

Reputation: 54148

  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)

Upvotes: 2

Temaledegn Yisfa
Temaledegn Yisfa

Reputation: 1

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.

Upvotes: 0

Related Questions