Python list extend() method

The list method extend() of Python is similar to append() method.They can add values at the end of the list.However,the only difference is that append() method can append items like integers or floating point numbers or list or tuple or string but the extend() method can append only iterable(meaning a sequence like list,tuple or string).We cannot append integers or real values with extend() method.

Link list append method

>>> ls=[12 ,56, 'New']
>>> ls.append( 23 ) #work fine
>>> ls
[12, 56, 'New', 23]
>>> ls.append([23 , 'Text']) #append list
>>> ls
[12, 56, 'New', 23, [23, 'Text']]
>>> #***using extend() method
>>> ls.extend( 90 )
Traceback (most recent call last): 
  File "<pyshell#14>", line 1, in <module> 
    ls.extend( 90 )
TypeError: 'int' object is not iterable
>>> ls.extend((23, 'happy')) #append tuple,work fine
>>> ls
[12, 56, 'New', 23, [23, 'Text'], 23, 'happy']
>>> ls.extend("Text") #work fine
>>> ls
[12, 56, 'New', 23, [23, 'Text'], 23, 'happy', 'T', 'e', 'x', 't']

In the above code example you can see that calling ls.extend(90) returns the error message
 
Traceback (most recent call last):
File “<pyshell#14>”, line 1, in <module>
ls.extend( 90 )
TypeError: ‘int’ object is not iterable

 
The last line “‘int’ object is not iterable” refers to 90,since 90 is an int type value and int type objects are not iterable.


Point to note

The extend() method is same as performing the operation:
 
O[ len(O): ] = iterable_object
    ‘O’ refers to the list object
    ‘iterable_object’ is the object of any iterable.

The ‘len(O)’ returns the number of elements in the list object ‘O’.Now,this means the expression ‘len(O):‘ point to the position next to the last element of the list object,that is also where the addition of new elements will begin.

Link :Python list

>>> newls=['list', 'tuple']
>>> newls[len( newls ):]=['string' , 'int']
>>> newls
['list', 'tuple', 'string', 'int']
>>> #~~~~~appending tuple object
>>> newls[len( newls ):]=('candcplsuplus is the best!',) #note the coma after the text
>>> newls
['list', 'tuple', 'string', 'int', 'candcplsuplus is the best!']
>>> #~~~~~~appending string or text
>>> newls[len( newls ):]='float'
>>> newls
['list', 'tuple', 'string', 'int', 'candcplsuplus is the best!', 'f', 'l', 'o', 'a', 't']

Do you notice if string is appended each character is treated as a different elements and the whole string is not considered.

Link :Python tuple



Leave a Reply

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