12

I have a for loop:

for x in range(1, 13):
    print("This was the average temperature in month number " + str(x) + " in Boston, 2014: ", Boston_monthly_temp(x))

This prints out the average monthly temperatures in Boston in 2014, such as:

This was the average temperature in month number 1 in Boston, 2014:  26.787096774193547

all the way up until Month Number 12 (December):

This was the average temperature in month number 12 in Boston, 2014:  38.42580645161291.

All in all, this for loop produces 12 lines.

However, I can't figure out how to store the results of this "for" loop into a single variable, like output_number_one.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Python noob
  • 173
  • 1
  • 1
  • 6
  • 2
    Since 'saving to a variable', you can ditch the `print` (because it is used for a side-effect and not value generation) in which case a [List Comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) would be an idiomatic approach (the link also shows how to explicitly build a list). – user2864740 Mar 24 '15 at 05:36

2 Answers2

15

Try this

result = []
for x in range(1,13):
    result.append((x, Boston_monthly_temp(x)))

Now result contains the x and avg

>>> for x, avg in result:
...     print ("This was the average temperature in month number " + str(x) + " in Boston, 2014: ", avg)
...
This was the average temperature ...
This was the average temperatu ...
[...]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
5

You could simply store the results in a dictionary:

d = {}
for x in range(1,13):
   d[x] = Boston_monthly_temp(x)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Saksham Varma
  • 2,122
  • 13
  • 15