What is the reason for this difference between lists and tuples? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: What is the reason for this difference between lists and tuples? (/thread-5251.html) |
What is the reason for this difference between lists and tuples? - Athenaeum - Sep-25-2017 I am a Python beginner, and recently I discovered a key difference between lists and tuples. If I write something like: list1 = list1.append(list2)...then list1 becomes a "NoneType" object. In other words if you pass an appended list to its own name, then it is replaced with a NoneType object. This isn't the case with tuples though...is there a reason for this? RE: What is the reason for this difference between lists and tuples? - buran - Sep-25-2017 first of all tuple has no attribute append. >>> x = (1,2) >>> y=(3,4) >>> x.append(y) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append'list1.append(list2) will append list2 the to the list1 in-place, i.e. what you should do >>> list1=[1,2] >>> list2=[3,4] >>> list1.append(list2) >>> list1 [1, 2, [3, 4]]as you can see list2 is added as 3-rd element in the list1. what I think you want to do is to use extend, instead of append >>> list1=[1,2] >>> list2=[3,4] >>> list1.extend(list2) >>> list1 [1, 2, 3, 4] RE: What is the reason for this difference between lists and tuples? - Athenaeum - Sep-25-2017 Sorry, I meant that this difference occurs when you use the __add__ method on a tuple, which I consider to be the equivalent of append for tuples. RE: What is the reason for this difference between lists and tuples? - buran - Sep-25-2017 __add__ is internal implementation that is called by + operator (i.e. concatenation) https://docs.python.org/3/library/stdtypes.html#typesseq read carefully note 6 and 3rd item in the bullet list Quote:Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below: apart from performance issue that is discussed, note that concatenating tuple is equivalent of extending a list, but extending the list has better performance |