-2

There is a scenario in which I got a little confused.

item = [5]
item.append(item.append(6))
print(item)

## This will result
[5, 6, None]

Why there is None as the last element of the list?

dipesh
  • 763
  • 2
  • 9
  • 27

2 Answers2

1

Because item.append(6) returns None, but adding 6 to the list during execution, so result expression converting to this:

item.append(None)

This behavior described here:

Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • ```item.append(6)``` returns ```None``` and what about 6 in the final result. – dipesh Jan 18 '20 at 13:26
  • 2
    it modifies the original piece of data and does not make a copy so item now has a 6 at the end of it, however you are appending the result of that function call to item as well resulting in the output that you have. – gold_cy Jan 18 '20 at 13:27
  • 2
    @dipesh 6 adding to the list when `item.append(6)` executed. – neverwalkaloner Jan 18 '20 at 13:29
  • 2
    It seems like I asked an unclear question. I edited the question now. Thank you very much for your explanation. I did have now clear point in this :) – dipesh Jan 18 '20 at 13:50
-1

item.append(6) appends 6 to the list and returns None.

Since you do item.append(item.append(6)), the inner append() appends 6 and return None, the outer append() appends the 'None' returned by the inner append() fn. just remove the outer append() function to solve your problem. Since the append() function returns only None, you cannot print the list like that. Follow the code below.

Like this:

item = [5]
item.append(6)
print(item)

I guess you missed the [] while writing the question.


Update after you updated your question: item.append(6) returns None, so when you append item.append(6) to your list again, then it'll append None to it.

Krissh
  • 67
  • 1
  • 7
  • 1
    The actual question should have been different. I edited the question now. @neverwalkaloner gave me more insight about the scenario here. I was just wondering why there is ```None``` as last element in the original list. And before the answer from this question I did not realize that appending items to the list will return ```None```. – dipesh Jan 18 '20 at 13:54
  • 1
    I must have missed this question here https://stackoverflow.com/a/16641831/9246099 – dipesh Jan 18 '20 at 13:57