Python list append() method

The Python append() method of list is one of the many methods of list.It’s sole purpose is to add an item at the end of the list object.The item to be appended is passed as an argument to the method.

If you do not what is list then you can visit the link given below.

Link : Python list : tips and tricks

A code example using the append() method is given below.

>>> ls=[67, 1637, 90]
>>> ls.append( 12 ) #append the number 12
>>> ls
[67, 1637, 90, 12]

Some points to note

Point 1

We can append only one item at a time to the list object using the append() method.However,the item to that can be appended is not limited to values(numbers or text).It can be also another object for instance it can be tuple or list itself.

>>> ls=[67, 1637, 90]
>>> ls1=[123 ,78]
>>> ls.append( ls1 ) #work fine
>>> ls
[67, 1637 , 90 , [123, 78]]
>>> #Using tuple
>>> tp=('New' , 'Text')
>>> ls.append( tp ) #work fine
>>> ls
[67, 1637 , 90 , [123, 78], ('New', 'Text')]

Link :Python Tuple : Tips and tricks

You can see the the list and tuple appended to the ‘ls’ are written inside ‘[]’ and ‘()’.


Point 2

We can also append an item to list object without using the ‘append()’ method.The formula is:
 
a[len(a):] = [x] :
  ‘a‘ is the list object and
  ‘x‘ is the item and it can be number of string or list or tuple
 
The len(a) gives the number of elements in the object ‘a’ and the expression ‘len(a):‘ points to the next position to the last element in the object.

>>> ls=[23 , 45]
>>> ls[ len(ls): ]=[23 , 45]
>>> ls
[23, 45, 23, 45]
>>> #Appending list object
>>> ls1=[23 , 1000 ]
>>> ls[len(ls):]=[ls1]
>>> ls
[23, 45, 23, 45, [23, 1000]]
>>> #appending tuple object
>>> tp=('New'  , "23546.43536")
>>> ls[len(ls):]=[tp]
>>> ls
[23, 45, 23, 45, [23, 1000], ('New', '23546.43536')]

TO know the difference between append() and extend() method visit Python extend method.



Leave a Reply

Your email address will not be published. Required fields are marked *