mutate or add elements to a list


Lists are mutative so that we can change the list with the help of operators and methods.

How to mutate or add elements to a list?

Lists are mutable or changeable, meaning their elements can be changed. We can use the assignment operator (=) to change an item or several items.

We can add one item to a list using the append() method and add a range of items using extend() method.
We can also use the plus operator(+) to combine two lists which are also called concatenation. The star operator(*) repeats a list for the given number of times mentioned.

There are few methods through which we can change manipulate the code:-

  • append() - It is used to add the elements into the list from the rare end.
  • insert() - It is used to add elements into the list at the given index.
  • extend() It is used to append iterable elements into the list from the rare end.
  • List Concatenation(+) - It is used to add two lists and creates the new list, but the old list will remain the same.

We can even add one item to a list using the append() method or can add a range of items using extend() method.

We can also use the plus operator(+) to combine two lists which are also called concatenation. The star operator(*) repeats a list for the given number of times mentioned.

Example no.1:

weblist = ["knoweldge2life 1", "knoweldge2life 2", "knoweldge2life 3"] weblist.append("knoweldge2life 4") print(weblist)

OUTPUT:

['knoweldge2life 1', 'knoweldge2life 2', 'knoweldge2life 3', 'knoweldge2life 4']

Example no.2:

web = ['knowedge2life'] print(web) bar = web bar += ['online website'] print(web)

OUTPUT:

['knowedge2life']
['knowedge2life', 'online website']