Jump to content

Square bracket in print statement: <generator object <genexpr> at 0x7f87fca11ba0>


zak100

Recommended Posts

Hi,

Following is the program similar to :

Storing the function in the list

fun_list2 = [ ]
for i in range(5):
    def fun2(e, iv=i):
        return e + iv
    fun_list2.append(fun2)


print([f(10) for f in fun_list2])

From the above link, I am able to understand the above code. However, I have problem in understanding the '[....]' in the print statement. If I run the above program without square brackets like:

print(f(10) for f in fun_list2)

I am getting the message:

Quote

<generator object <genexpr> at 0x7f87fca11ba0>

Somebody please guide me.

 

Zulfi.

Link to comment
Share on other sites

Do you realize that you can use Python Debugger and figure out by yourself the all answers to questions about your Python scripts which you are starting on this forum?

Enter "Python online debugger" in net search engine, copy'n'paste Python script in it, and observe how variables are changing with each "step into" and "step over", line by line..

e.g. https://www.onlinegdb.com/online_python_debugger

It will be simply faster for you, as you won't have to wait till somebody answered your question here..

 

1 hour ago, zak100 said:

However, I have problem in understanding the '[....]' in the print statement. If I run the above program without square brackets like:


print(f(10) for f in fun_list2)

I am getting the message:

Quote

<generator object <genexpr> at 0x7f87fca11ba0>

Somebody please guide me.

[ .... ] initializes array

print( [ ] ); is just printing newly dynamically created array..

It is not much different from using print([1,2,3]);

 

If you want to do it without generating new array, you can write:

print(fun_list2[0](10))
print(fun_list2[1](10))
print(fun_list2[2](10))
print(fun_list2[3](10))
print(fun_list2[4](10))

or you can make for loop like:

for i in range(5): print(fun_list2[i](10))

or even better:

for f in fun_list2: print(f(10))

Edited by Sensei
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.