0

Let's say I have the following code:

string = "XxXxXx"
print(string.lower())
print(string.upper())

How could I use a list instead along the lines of:

string = "XxXxXx"
list = [lower(), upper()]
for i in list:
    print(string.i)

Obviously the code above does not work at all and the problem I'm working on is way more complicated. But if I could make the example above work, it would really take care of my problem!

1
  • Beside the point, but list is a bad variable name since it shadows the builtin list type. In example code it's not a big problem, just a bit confusing, but in more involved code, it's better to use a more descriptive name, or at least something like L or lst. Cf. TypeError: 'list' object is not callable. Commented Nov 2, 2022 at 22:37

1 Answer 1

1

Functions (and methods) are first class objects in python. You can therefore store them in a list just like you would anything else.

If you want to be able to apply the functions to arbitrary strings, use the unbound function objects in the class:

string = "XxXxXx"
func_list = [str.lower, str.upper]
for i in func_list:
    print(i(string))

If you want to only apply the functions to your special string, you can store the bound methods in a list instead:

string = "XxXxXx"
func_list = [string.lower, string.upper]
for i in func_list:
    print(i())

In both cases, the () operator is what calls the function. The function name by itself is a reference to the object. In the first case, the . operator does not do anything surprising. In the second case, since you invoke it on an instance of a class, it binds the function object in the class to the instance, creating a bound method that has an implicit self argument.

Sign up to request clarification or add additional context in comments.

4 Comments

@AlexReynolds. List is not a keyword, it's the name of a builtin class, but your general thought is correct. Will fix momentarily.
Whatever you want to call it, call it that, but don't use keywords to name variables unless you want headaches down the road.
@AlexReynolds. Yes, you are right, but using correct terminology is important too. You can't really be meaningfully pedantic about one but not the other.
@Alex It really isn't a keyword. Keywords can't be assigned to, like None. It's a builtin type.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.