Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 384
Shaken_not_stirred. Avatar asked Dec 24 '22 04:12

Shaken_not_stirred.


1 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)
like image 99
kindall Avatar answered Apr 06 '23 01:04

kindall