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

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.

5 Likes

3 posts were merged into an existing topic: Why does my code return None?

6 posts were split to a new topic: Ways we could extend the list

This is how I coded this lesson

#Write your function here
def append_size(lst):
  total_elements = len(lst)
  lst.append(total_elements)
  return lst


Here’s how I did it

def append_size(lst):

  size = len(lst)
  
  lst.append(size)
  
  return lst