-1

I read this post: What's the difference between [a] + [b] and [a].extend([b])?

It says that in terms of lists "+" between lists creates a new list and extend changes the list which is operated on.

[1,2,3] + [4]

vs

[1,2,3].extend([4])

Is there any way to get this information without diving into the documentation, but only using the interpreter using help() or dir() for example?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
David
  • 2,926
  • 1
  • 27
  • 61
  • 2
    Your question is very meta. You are better off looking at the online docs... or are you planning to migrate to a place without internet? ;) – cs95 Apr 07 '19 at 09:31

3 Answers3

2

Limiting yourself to the interpreter, one way to do it is through the instance method's docstring. You can access it through help(list.extend) or through the __doc__ property. For instance:

>>> list.extend.__doc__
'Extend list by appending elements from the iterable.'

As for the + operator merging two lists, that's only possible thanks to operator overloading by the list class. Behind the scenes, it's implemented through a special method called __add__. Using the same approach as above:

>>> list.__add__.__doc__
'Return self+value.'

That being said, the online docs are certainly a less convoluted way to access this information.

Omar
  • 575
  • 5
  • 14
1

This might not be what you're after, but you can easily check for or verify this behavior from the interpreter.

>>> l1 = [1,2,3]
>>> l2 = [4]
>>> l1 + l2, l1, l2
([1,2,3,4], [1,2,3], [4])
>>> l1.extend(l2), l1, l2
(None, [1,2,3,4], [4])
Avish
  • 4,516
  • 19
  • 28
1

A. If a function (method) modifies data and does not return the result, then is must have mutated objects passed to it as function inputs. This is called in-place modification.

Such functions often deliberately return nothing (None). This convention is nicely described at list.sort:

This method modifies the sequence in place ..... To remind users that it operates by side effect, it does not return the sorted sequence

Note that there exists a technique called "Fluent interface" based on method chaining requiring an opposite approach.


B. you can always check with id() if a new object was created

>>> l1 = [1,2,3,4]
>>> l2 = ['A','B','C']
>>> id(l1), id(l2), id(l1+l2)
(139855120180552, 139855123390792, 139855123880392)
VPfB
  • 14,927
  • 6
  • 41
  • 75