Jump to content

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

Featured Replies

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.

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

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.