When we append the list's length to itself, what value would be appended?


#1

Question

In this code challenge, we are appending the list’s length to itself. If we append the list’s length to itself, what value would be appended, the previous length or the length after the value was appended?

Answer

Following the order of operations, this will calculate the list’s length first, then append that value to it.

To explain what this means, say we had a list of elements
list = [10, 20, 30].

If we call this method on the list,
.append(len(list))

because of operator precedence, the expression inside parentheses () will be evaluated first. This will evaluate to the current length of the list, 3, before it is appended, and essentially become the same as running this,
.append(3)

which would update the list to
[10, 20, 30, 3]

If, instead, the .append() happened first, then the value of len(list) might have been 4 instead, but because of operator precedence, this issue will not occur.


FAQ: Code Challenge: Lists - Append Size
#2

Can’t I store ‘appended list’ to a new list and return the new list?
Like below…

def append_size(lst):
new_lst = lst.append(len(lst))
return new_lst

print(append_size([23, 42, 108]))

It returns None when I proceed it…

Thanks,


#3

the advantage of mutable data types (like lists) is that we can append items to the existing list rather then creating a new list. These mutations are more efficient then constructing new lists every time

of course there are other ways we can construct new lists, by adding two lists together for example:

new_lst = lst + [len(lst)]

#4

Hi @lucylee3476390680,

Though the append method of list does add the specified item to the end of the list on which it is called, its return value is None. Accordingly, this adds the value of len(lst) to the end of lst, then assigns None to new_lst:

new_lst = lst.append(len(lst))