What is the use of .append in python?

Question:

I am new at python and I still don’t get the concept of .append in python. Why do we use .append if we could just edit the original code to add new value?
Ex:
What I am being taught to do:

random_list = ['cat', 'dogs' 2, 4,]

Let’s say I wanted to add food to random_list, why can’t I type it directly to the random_list?
The same thing for other code functions like .pop and .extend

Asked By: newcodester

||

Answers:

Once you’ve defined the list, you may need to add to it afterward.

Now, you do have the option of taking the long way to write out the entire list and adding the new element at the end, but not only is that annoying to do, but sometimes (with very long lists or many new elements to append) it’s really just not feasible. append gives us an easy way to add to the list without having to completely redefine it every time.

Imagine if you wanted a list with every number that’s divisible by 23 between 1 and 1,000,000,000. There’s no way you could do that by hand, so instead we can:

mylist = []

for n in range(1000000000):
    if n%23 == 0:
        mylist.append(n)
Answered By: Christian Trujillo

Imagine having a big dictionary that you want to get all the keys of in a list
and all the values of in another list.
Will you type all the keys or values manually or you want something to add them quickly and easily for you?
Here is an example:

ages = {
   "david_age":12,
   "gary_age":14,
   "simon_age":10,
   "maddison_age":16
}
keys_list = []
values_list = []

for key , value in ages.items():
    keys_list.append(key)
    values_list.append(value)
Answered By: CTRLDON
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.