Ma0
Ma0

Reputation: 15204

Modifying List Values

I am a bit puzzled by the behavior of two functions i wrote for the modification of a list that is given as input. In my mind, both should be doing the same thing but this is not the case. Take a look:

def headerFormat1(list1):
    char_to_remove = ['(', ')']
    list2 = list1[:]
    list1 = []
    for headers in list2:
        headers = headers.replace(' ', '_')
        for character in char_to_remove:
            headers = headers.replace(character, '')
        list1.append(headers)
    del list2
    return list1

def headerFormat2(list1):
    char_to_remove = ['(', ')']
    for i, headers in enumerate(list1):
        list1[i] = headers.replace(' ', '_')
        for character in char_to_remove:
            list1[i] = headers.replace(character, '')
    return list1

theList = ['I want Underscores Instead', 'R(e(m(o(v(e()P)a)r)e)n)t)h)e)s)e)s', 'LetMeBe']
print(headerFormat1(theList)) #prints: ['I_want_Underscores_Instead', 'RemoveParentheses', 'LetMeBe']
print(headerFormat2(theList)) #prints: ['I want Underscores Instead', 'R(e(m(o(v(e(Parentheses', 'LetMeBe']

And i mean ok, the first one works as it is supposed to altough i find the list duplication redundant and possibly not necessary\overkill(?)

But the second one.. Whats that strange thing with the parentheses removal? Also, even though it does not work properly, it suggests that modifying the list elements in-place is possible (removes ')') but then why aren't the spaces replaced?

Thanks.

Upvotes: 0

Views: 52

Answers (1)

MONTYHS
MONTYHS

Reputation: 924

You are changing list1[i] every time with original headers Check below code it works

def headerFormat1(list1):
    char_to_remove = ['(', ')']
    list2 = list1[:]
    list1 = []
    for headers in list2:
        headers = headers.replace(' ', '_')
        for character in char_to_remove:
            headers = headers.replace(character, '')
        list1.append(headers)
    del list2
    return list1

def headerFormat2(list1):
    char_to_remove = ['(', ')']
    for i, headers in enumerate(list1):
        headers = headers.replace(' ', '_')
        for character in char_to_remove:
            headers = headers.replace(character, '')
        list1[i]=headers
    return list1

theList = ['I want Underscores Instead', 'R(e(m(o(v(e()P)a)r)e)n)t)h)e)s)e)s', 'LetMeBe']
print(headerFormat1(theList))
print(headerFormat2(theList))

Upvotes: 1

Related Questions