Python lowercase list comprehension failing tests when it seems to be right?

Viewed 141

I'm doing a Python course that involves completing numerous online questions, and the task seemed really simple (take a list of strings and convert it to lowercase). However, my code fails no matter what I try. I've tried list comprehension and loops, but to no avail - it just says failed test. Here is the code below:

def lowercase(strings):
    """takes a list strings and replaces string with lowercase words"""
    strings = [x.lower() for x in strings]
    return strings   

strings = ['LOWER', 'CASE', 'SENTENCE']
lowercase(strings)
print(strings) 

The part I am supplied is:

def lowercase(strings):
    """takes a list strings and replaces string with lowercase words"""


strings = ['LOWER', 'CASE', 'SENTENCE']
lowercase(strings)
print(strings) 

So I'm only allowed to write code within the function that changes 'strings' to lowercase (I can write code under the doc string, but I can't modify anything else such as deleting those three lines of test code). Because their test declares strings and calls the function under my code, it seems to just overwrite anything I write! I feel like I'm going crazy as this is a beginner question and I can't make it pass the test. What I am doing wrong? Thanks!

3 Answers

You need only a minor change: modify the list in place using a slice assignment, rather than creating a new list. You then don't need to return it (in fact, the Python convention is to not do so).

def lowercase(strings):
    """takes a list of strings and replaces each with lowercase version"""
    strings[:] = (x.lower() for x in strings)

Your problem is that the function you have makes a copy of strings inside of it, and returns the copy. Instead, you want to modify the list in place.

Here's one way you can do it:

def lowercase(strings):
    """takes a list strings and replaces string with lowercase words"""
    for i, x in enumerate(strings):
        strings[i] = x.lower()

strings = ['LOWER', 'CASE', 'SENTENCE']
lowercase(strings)
print(strings)
#['lower', 'case', 'sentence']

Instead of the list comprehension (which creates a new list), iterate over the indices of strings and modify each element.

With same List Comprehension code try this one

strings = ['LOWER', 'CASE', 'SENTENCE']
strings = lowercase(strings)

print(strings)
Related