Why would we append our data rather than just modify the list?

Wouldn’t it be better practice to go back to the original coded list to add additional items? I feel like if you have a bunch of "append"s throughout the code and have to go back to adjust something it could be a headache to find and fix if you have 20 "append"s. Can someone with experience in the field shed some light on why this would be a useful command and why you wouldn’t just go back and edit the original?

Thanks!

If that were possible, yes, on the assumption we discover this data will be needed in all session runs. But programs are dynamic and lots of data is generated by the program (and user) that we couldn’t possibly foresee. That’s why we have mutation methods so our data structures can be updated on the fly, dynamically.

33 Likes

If we using append, are there a way to insert the new data with the location that we want it. For example, I want to insert an integer to a sort list/array? What syntax to use for that?

append() can only do as the name suggests… append, which means add to the end. The way to insert an element is with, wait for it… The insert method. We supply two arguments:

  • the index we wish to insert before.
  • the value we wish to insert
>>> a = [1, 2, 4, 5]
>>> a.insert(2, 3)
>>> a
[1, 2, 3, 4, 5]
>>> 
16 Likes

I suppose you could load a list from a text file, then append the text file as you go and next time you run the code it’ll be present, as it added information to a text file, not just stored it in memory temporarily.

Also, we use append because we don’t always know the value of the data we will need to append, so appending ‘variable’ rather than raw data is difficult to predict it could be the resulting value of complex calculations or time dependent data etc.