[Tutor] assignment question
Hello, Why does the following not return [1,2,3,4] ? x = [1,2,3].append(4) print x None ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] assignment question
On 12/11/2007, Ryan Hughes [EMAIL PROTECTED] wrote: Why does the following not return [1,2,3,4] ? x = [1,2,3].append(4) print x None List methods like .append() and .sort() modify lists in-place, as opposed to creating new lists. To remind you of this, those methods return None instead of returning the modified list. Otherwise (if .append() returned the modified list), you might be tempted to write code like this: x = getSomeList() y = x.append(3) and forget that x and y are the same list. If you want to join two lists together to make a new one, you can use +: x = [1, 2, 3] + [4] x [1, 2, 3, 4] Hope this helps, -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] assignment question
On Sunday November 11, 2007, Ryan Hughes wrote: Hello, Why does the following not return [1,2,3,4] ? x = [1,2,3].append(4) print x None The reason is that the append method does not return anything. In effect, the expresison [1,2,3].append(4) temporarily causes 4 to be appended to the (unnamed) list. However the assignment x = blah sets the variable x equal to the result of the expression blah (which in this case is None, since append does not return anything). In contrast, consider the following interaction: x = [1,2,3] x.append(4) print x [1, 2, 3, 4] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] assignment question
Ryan Hughes wrote: Hello, Why does the following not return [1,2,3,4] ? x = [1,2,3].append(4) print x None because the append() method doesn't return a copy of the list object; it just modifies the list itself. so your code constructs a list object with 3 elements, appends a fourth element to it, and throws that list object away, keeping only the return value of append(). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] assignment question
Append modifies the array as a side effect. It has no meaningful return value. x = [1, 2, 3] x.append(4) print x [1, 2, 3, 4] - Jeff Younker - [EMAIL PROTECTED] - 510.798.5804 - On Nov 11, 2007, at 8:21 PM, Ryan Hughes wrote: Hello, Why does the following not return [1,2,3,4] ? x = [1,2,3].append(4) print x None ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor