1

I thought in Python I am allowed to perform method chaining.

basket = [1,3,2,4,6,8]

basket.append(7)
basket.sort()
basket.reverse()

This works.

basket.append(7).sort().reverse()

This does not.

AttributeError: 'NoneType' object has no attribute 'sort'

I am not sure what is going on here, but I assume that happens because in place methods result in "NoneType" result = basket.sort() and therefore the second method will be performed on the result and not the original object.

Can anyone help me how to do these operations without writing a new line for each method?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Data Mastery
  • 1,555
  • 4
  • 18
  • 60
  • 2
    `.append()` doesn't return anything, that's why. You are allowed to method chain, but they need to return the object you then want the next method to be able to call. Try: `print(basket.append(7))` and then do `print(basket.sort())` None of these probably do what you think. – Torxed Nov 06 '19 at 08:11
  • 1
    The `append()` and `sort()` methods work in place and return `None`. The assignment, as you pointed out correctly, assigns `None` – Fourier Nov 06 '19 at 08:12
  • 2
    It's an explicit design choice that those methods return `None`, since that emphasises that they work *in place*: https://stackoverflow.com/a/58269482/476 – deceze Nov 06 '19 at 08:13

1 Answers1

6

Because append sort and reverse are all "in-place" methods, so they don't return anything, instead they update the original list, the best way would be:

print(sorted(basket + [7], reverse=True))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • thank you, already thought so. To be honest, I don´t really like the way this looks. I most of the time program with "Pandas", so I can see now why most of the methods are not "in place" :/ – Data Mastery Nov 06 '19 at 08:16