I m trying to learn to code in a "pythonic way".
The original code is working, results and displays the expected results. The new code is giving: "<generator object at 0x0000017862039510>". Why then ?
Original code:
a={
'AA':-5,
'BB':-8,
'C':15,
'D':-85,
'E':24
}
for i in a.values():
if i<0:
print(i)
New code :
a={
'AA':-5,
'BB':-8,
'C':15,
'D':-85,
'E':24
}
print(i for i in a.values() if i<0 )
Thank you !
CodePudding user response:
i for i in a.values() if i<0
is a generator - it doesn't resolve to a sequence of values unless something iterates it. For parsing reasons, you can't have the generator by itself without enclosing it in grouping parenthesis
>>> i for i in a.values() if i<0
File "<stdin>", line 1
i for i in a.values() if i<0
^
SyntaxError: invalid syntax
>>> (i for i in a.values() if i<0)
<generator object <genexpr> at 0x7f2a54b3ac80>
print
just takes the string representation of objects. It doesn't try to iterate them. So, you get the string representation of the generator itself. Other objects are different - lists and tuples for instance, do iterate their initialization value.
>>> list(i for i in a.values() if i<0)
[-5, -8, -85]
>>> tuple(i for i in a.values() if i<0)
(-5, -8, -85)
List comprehensions do the same thing - build lists using the same generator semantics
>>> [i for i in a.values() if i<0]
[-5, -8, -85]
CodePudding user response:
To print out the values of the generator, separated by a newline, you can use .join
method which will create a string by joining each element of the generator with a newline (note that the values in the generator must be strings (in this case they need to be explicitly converted)):
print('\n'.join(str(i) for i in a.values() if i < 0))
CodePudding user response:
The expression which is written in that print statement of yours is a generator expression. In your original code, you iterate through each key-value pair in your dictionary and print the value. In your new code, you are attempting to print the result of that expression which is an object and not a series of print statements.