Reputation: 1
This is my code:
temps = (345, 9876, 23, 100, 567)
new_temps = (temps / 10 for temp in temps)
print(new_temps)
The result is an error...
<generator object <genexpr> at 0x7fc8101f76d0>
Upvotes: 0
Views: 64
Reputation: 13059
You are using a generator expression.
Either you need to use the corresponding list comprehension by using [
... ]
instead of (
... )
:
temps = (345, 9876, 23, 100, 567)
new_temps = [temp / 10 for temp in temps]
print(new_temps)
gives
[34.5, 987.6, 2.3, 10.0, 56.7]
or you need to iterate over the generator:
temps = (345, 9876, 23, 100, 567)
new_temps = (temp / 10 for temp in temps)
for temp in new_temps:
print(temp)
gives
34.5
987.6
2.3
10.0
56.7
You can also just convert it to a list (which works by iterating over it):
temps = (345, 9876, 23, 100, 567)
new_temps = (temp / 10 for temp in temps)
print(list(new_temps))
gives
[34.5, 987.6, 2.3, 10.0, 56.7]
(Iterating e.g. with a for
loop will also work with the list comprehension used in the first option, although if you have a lot of items and all you are going to do is iterate once over it, then it is more efficient on memory to use the (
... )
form.)
I have also corrected a bug in the generator expression - should be temp / 10
, not temps / 10
.
Upvotes: 0
Reputation: 690
if you want to convert temps into list you can use:
list(temps)
Out: [345, 9876, 23, 100, 567]
But you can achieve your requirement without any conversion using list comprehension you can get your answer:
temps = (345, 9876, 23, 100, 567)
new_temps = [temp / 10 for temp in temps]
print(new_temps)
Out: [34.5, 987.6, 2.3, 10.0, 56.7]
Upvotes: 0
Reputation: 354
You declare lists in python with [ ], also your for is calling all your list, not the element, which is "temp" not "tempts". It would be like this:
temps = [345, 9876, 23, 100, 567]
new_temps = [temp / 10 for temp in temps]
print(new_temps)
>> [34.5, 987.6, 2.3, 10.0, 56.7]
Good luck with your travel in Python!
Upvotes: 0
Reputation: 530960
First, temps
is a tuple, not a list. A list would use square brackets:
temps = [345, 9876, 23, 100, 567]
For your use, it doesn't matter if it is a tuple or list, though.
Second, (temps / 10 for temp in temps)
is a generator expression, not a list comprehension. You want
new_temps = [temps/10 for temp in temps]
Upvotes: 0
Reputation: 155353
Using parentheses around a comprehension makes it a generator expression; if you want a list
comprehension, use square brackets:
new_temps = [temps / 10 for temp in temps]
Side-note: Your original temps
isn't a list
either (because you used parentheses, not square brackets as the delimiter); it's a tuple
(similar to a list
, but immutable). It works just fine in this case since you're not trying to modify it.
Upvotes: 2