-2

I am not clear why second output doesnt give me any results although the same line gives me results after the for loop. You can comment out one by one and check the output.

Thanks in advance !

three_rows = ["Albuquerque,749", "Anaheim,371", "Anchorage,828"]
#print(three_rows)   #1st output
#three_rows[0]       #2nd output -- no response!

final_list = []
for row in three_rows:
    split_list = row.split(',')
    final_list.append(split_list)

#print(three_rows)   #3rd output -- prints the whole list(expected)
#three_rows[1]       #4th output -- prints the 2nd element(expected)
#print(final_list)   #5th output -- prints the whole list(expected)
#final_list[0]       #6th output -- prints the first element(expected)
user1951
  • 1,411
  • 1
  • 10
  • 8
  • 6
    Use `print(three_rows[0])` in second output – arshovon Oct 14 '17 at 16:55
  • Great, that works, but do you have any explanation for it ? See my comment on the first answer, you are completely right but I m missing the explanation... – user1951 Oct 15 '17 at 07:02

1 Answers1

0

Check this python function return value.

So Python function always returns something at the end. In your case, for 2nd output, there are lines following it like the for loop etc. But for the 4th and 6th output(assuming you uncomment only one of them), it coincidentally happens to be the last code line of the module and hence during the exiting of the execution of your program, it returns whatever output comes from that and subsequently it gets printed on the console.

Community
  • 1
  • 1
Prasad
  • 5,946
  • 3
  • 30
  • 36
  • If I uncomment 3rd and 4th comment, I get two outputs. If I uncomment 3rd 4th and 5th output, I get two outputs for 3rd and 5th, 4th is ignored. The only guaranteed way to get the 4th output is to use 'print', but I am missing the explanation ! – user1951 Oct 15 '17 at 07:01
  • Exactly. 3rd comment is print statement. It will print regardless. But 4th and 6th statement just evaluates some elements in array. And if it happens to be last non-comment line, the evaluated statement value will be returned by module/function. In short, Python function always returns a value even if you are not explicity returning. Go through that thread. It has better explanations. – Prasad Oct 15 '17 at 07:35