简体   繁体   中英

List comprehension in Python outputs None for function string evaluation

Trying to pass a list in Python through a function I have defined, however when I run the code I get 'None' as the output.

For reproducibility I'll use a simple example in which I want to make all words in a string uppercase.

def upcase(x):
    print(x.upper())

upcase("word")

This of course gives:

WORD

But now, if I attempt to apply my function to an entire string, as in the following:

randoms = ['chicken', 'window', 'carpet', 'lampshade', 'crosswalk']

randoms_upcased = [upcase(x) for x in randoms]
print(randoms)
print(randoms_upcased)

I get:

CHICKEN
WINDOW
CARPET
LAMPSHADE
CROSSWALK
['chicken', 'window', 'carpet', 'lampshade', 'crosswalk']
[None, None, None, None, None]

Whereas the output I desire is this.

['chicken', 'window', 'carpet', 'lampshade', 'crosswalk']
['CHICKEN', 'WINDOW', 'CARPET', 'LAMPSHADE', 'CROSSWALK']

Is this possible? Any help gratefully receieved.

Your upcase function prints out the result, but it doesn't return anything. Since you aren't specifying a return value, it defaults to returning None . You'll want to add an explicit return:

def upcase(x):
    x = x.upper()
    print(x)
    return x

I think it is because the function upcase(s) is made to just print the string s in uppercase but it does not return anything. It should work if you return the uppercase string from the function.

You need to return the string you are printing.

This should work:

def upcase(x):
    return (x.upper())

First store result in another list( z ) then return ( z ) in the function:

def upcase(x):
    z = ([y.upper() for y in x])
    return z
l1 = ['chicken', 'window', 'carpet', 'lampshade', 'crosswalk']
upcase(l1)

output:

['CHICKEN', 'WINDOW', 'CARPET', 'LAMPSHADE', 'CROSSWALK']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM