Why is the interpreter is returning a 'reference'?

N

Nir

k = ['hi','boss']
k ['hi', 'boss']
k= [s.upper for s in k]
k
[<built-in method upper of str object at 0x00000000021B2AF8>, <built-in method upper of str object at 0x0000000002283F58>]

Why doesn't the python interpreter just return
['HI, 'BOSS'] ?

This isn't a big deal, but I am just curious as to why it does this.
 
E

emile

k = ['hi','boss']

k ['hi', 'boss']
k= [s.upper for s in k]

s.upper is a reference to the method upper of s -- to execute the method
add parens -- s.upper()

Emile

[<built-in method upper of str object at 0x00000000021B2AF8>, <built-in method upper of str object at 0x0000000002283F58>]

Why doesn't the python interpreter just return
['HI, 'BOSS'] ?

This isn't a big deal, but I am just curious as to why it does this.
 
N

Ned Batchelder

k = ['hi','boss']

k ['hi', 'boss']
k= [s.upper for s in k]
k
[<built-in method upper of str object at 0x00000000021B2AF8>, <built-in method upper of str object at 0x0000000002283F58>]

Why doesn't the python interpreter just return
['HI, 'BOSS'] ?

This isn't a big deal, but I am just curious as to why it does this.

You have to invoke s.upper, with parens:

k = [s.upper() for s in k]

In Python, a function or method is a first-class object, so "s.upper" is
a reference to the method, "s.upper()" is the result of calling the method.
 
Z

Zachary Ware

k = ['hi','boss']

k ['hi', 'boss']
k= [s.upper for s in k]
k
[<built-in method upper of str object at 0x00000000021B2AF8>, <built-in method upper of str object at 0x0000000002283F58>]

Why doesn't the python interpreter just return
['HI, 'BOSS'] ?

It's just doing exactly what you are telling it to :). Your list
comprehension is constructing a list consisting of the 'upper' method
(which are themselves objects, able to be passed around just like any
other value) for each string object in list 'k'. Consider this:
k = ['hi', 'boss']
s = k[0]
s 'hi'
s.upper # this just accesses the 'upper' attribute of 's',
which turns out to be its 'upper' method
'HI'

Change your comprehension to actually call the upper method like so:
"k = [s.upper() for s in k]". It will do what you expected with that
change.

Hope this helps,
 
J

John Gordon

In said:
k = ['hi','boss']

k ['hi', 'boss']
k= [s.upper for s in k]
k
[<built-in method upper of str object at 0x00000000021B2AF8>, <built-in method upper of str object at 0x0000000002283F58>]
Why doesn't the python interpreter just return
['HI, 'BOSS'] ?
This isn't a big deal, but I am just curious as to why it does this.

Because you typed 'str.upper' instead of 'str.upper()'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top