Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function, to apply a function to a list

I am trying to write a function, that applies a function to a list. I am trying to capitalise all the words in a list but can't get it to work. Here is what I've done so far:

list = ("hello", "this", "is", "a", "test")

def firstFunction(x):
    return list.upper()

print firstFunction

The error I get is:

<function firstFunction at 0x0000000002352A58>

I'm really stuck on what to do next, any help would be greatly appreciated.

EDIT: I've just changed it but it's still not working:

mylist = ("hello", "this", "is", "james")

def firstFunction(x):
    return may(lambda: x.upper(), mylist)

print firstFunction()
like image 668
JaAnTr Avatar asked Dec 28 '25 16:12

JaAnTr


2 Answers

That isn't an error. It is the function's address in memory. You are seeing it because you didn't invoke the function.

Overall, there are three problems with your code:

  1. You are not invoking the function. Adding (...) after it will do this.
  2. You are not passing in an argument to the function, which it requires.
  3. There is no upper method on a tuple (list in this case is a tuple).

Below is a fixed version of the code that does what I think you want:

# Don't name a variable 'list' -- it overshadows the built-in.
lst = ("hello", "this", "is", "a", "test")

def firstFunction(x):
    return tuple(y.upper() for y in x)

print firstFunction(lst)

Output:

('HELLO', 'THIS', 'IS', 'A', 'TEST')

Here are some references on everything done here:

http://docs.python.org/2/reference/compound_stmts.html#function-definitions

https://wiki.python.org/moin/Generators

http://docs.python.org/2.7/library/stdtypes.html#str.upper

While other answers are great, I want to mention that there's already a function in python, called map(), and it does almost exactly what you need:

Apply function to every item of iterable and return a list of the results..... The iterable arguments may be a sequence or any iterable object; the result is always a list.

So you code becomes

print map(str.upper, lst)

or, if you need a tuple, then:

print tuple(map(str.upper, lst))

You don't need anonymous lambda function here, because str.upper() accepts one argument. I think there's a debate about how pythonic this functional programming is, but I personally like it sometimes.

like image 22
Roman Pekar Avatar answered Dec 31 '25 08:12

Roman Pekar