Why do sequence for loops don't seem to work well in Python?

Issue

I’m trying to convert every string in a list to it’s lowercase format using this function:

def lower_list(strings):
    for string in strings:
        string = string.lower()
    return strings

But this implementation is not working, however when using the range funtion and I iterate using an index:

def lower_list(strings):
    for i in range(len(strings)):
        strings[i] = strings[i].lower()
    return strings

I do get every element on my list converted to lowercase:

> print(lower_list(mylist))
['oh brother where art thou', 'hello dolly', 'monsters inc', 'fargo']

But with the first implementation I get the original list with Uppercase values, am I missing something important in how the for loop works?

Solution

In the first case, all you are doing is storing the lowercase value in a variable, but the list is untouched.
In the second case, you are actually updating the value in the list at that index.

You can also use a lambda function here:

def lower_list(strings):
    return list(map(lambda x: x.replace(x, x.lower()), strings))

List comprehension is the easiest and the best:

def lower_list(strings):
    return [string.lower() for string in strings]

Answered By – NYC Coder

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.