-1

I have a simple problem which I've solved but it would be great if someone could explain why for loops do this in python and if there is a more elegant way. Really sorry if this is a dumb question - I have done my best to try multiple methods and look at related questions, but I still unsure why it doesn't work.

I've read this post, but it doesn't quite explain my issue: for loop only returning the last word in a list of many words

If I print x, it returns every month name perfectly.

monthName = []

for i in df["Month_Number"]:
    x = calendar.month_abbr[i]
    print(x)

The below stores the result (month names) it in a nice clean list (which is great).

monthName = []

for i in df["Month_Number"]:
    x = calendar.month_abbr[i]
    monthName.append(x)

I would then go on to solve my problem by doing this:

df["Month_Name"] = monthName

Why does the following ONLY return "NONE" when i integrate into the loop?

monthName = []

for i in df["Month_Number"]:
    x = calendar.month_abbr[i]
    df["Month_Name"] = monthName.append(x)

Why does the following only return the last value:

for i in df["Month_Number"]:
    df["Month_Name"] = calendar.month_abbr[i]

I understand (to some degree) as to why append returns none, but was more interested in understanding why other approaches only return the LAST value.

AdrianC
  • 383
  • 4
  • 18
  • Because `monthname.append()` returns `None`, not the appended list. – tripleee Apr 15 '18 at 08:11
  • 1
    Possible duplicate of [Why does append return none in this code?](https://stackoverflow.com/questions/16641119/why-does-append-return-none-in-this-code) – tripleee Apr 15 '18 at 08:13

1 Answers1

2

First way, append() doesn't return anything, so its return value will be None.

Second way, nothing is "being returned", you are overwriting the value within a loop, then only inspecting the value of the entire df["Month_Name"] column after the final iteration, which by definition, will be the last value.

I think using loops is the wrong approach here, you should be using apply or map functions instead, but if you wanted a loop, I might suggest this

df["Month_Name"] = [calendar.month_abbr[i] for i in df["Month_Number"]]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Firstly, thank you for indulging this - I appreciate it. Your suggestion worked so thank you. How is this different to my approach? They look the same except you've done it in a one-line list comprehension. I was going to create a dictionary of Month Numbers : Month Names and then map it back, but I wanted to test other ways. – AdrianC Apr 15 '18 at 08:17
  • The `append()`, then `=` approach and the list-comprehension are the same. Just less code and no temporary list variable lying around – OneCricketeer Apr 15 '18 at 08:20