Working With Lists In Python Programing - Coderz*United

Working With Lists In Python Programing




 

append() :Appending elements to a list 

Adds a single item to the end of the list. Does not return a new list, just modifies the original.


L=[12,13,14,15

L.append(16) 

print(L)

Out[1]: [12, 13, 14, 15, 16] 


L2=[21,22

L.append([21,22]) 

print(L)

Out[2]: [12, 13, 14, 15, 16, [21, 22]] 

print(L2)

Out[3]: [21, 22] 


L3=L.append(32) 

print(L3)

Out[4]: [12, 13, 14, 15, 16, [21, 22], 32] 

extend() :Appending multiple elements to a list 

append() adds one element to a list, extend() can add multiple elements from a list supplied to it as an argument. Returns no value. 

L3=L.append(34,37) 

TypeError: append() takes exactly one argument (2 given) 

print(L)

Out[1]: [12, 13, 14, 15, 16, [21, 22], 32] 

L.extend([43,46]) 

print(L)

Out[2]: [12, 13, 14, 15, 16, [21, 22], 32, 43, 46] 

L.extend(23,24) 

TypeError: extend() takes exactly one argument (2 given) 


List.insert(<pos>,<item>)

  • Append() and extend() insert the element(s) at the end of the list 

  • If you want to insert an element somewhere in between or any position of your choice, insert() method is used. 

  • <pos> is the index of the element before which the second argument is to be added 

  • Returns no value 

print(L)

Out[1]: [11, 12, 13, 14, 15] 

L.insert(5,19) 

print(L)

Out[2]: [11, 12, 13, 14, 15, 19] 

L.insert(9,19) 

print(L)

Out[3]: [11, 12, 13, 14, 15, 19, 19] 

L.insert(-9,19) 

print(L)

Out[4]: [19, 11, 12, 13, 14, 15, 19, 19] 

L.insert(3,19) 

print(L)

Out[5]: [19, 11, 12, 19, 13, 14, 15, 19, 19]


Updating elements to a list 

To update or change and element of the list in place, you just have to assign new values to the element’s index in list as per Syntax :

L[index] = <new value>

L=[11,12,13,14,15

L[0]=21 

print(L)

Out[1]: [21, 12, 13, 14, 15] 

L[5]=21

IndexError: list assignment index out of range 



Deleting Elements from a List 

The del statement can be used to remove an individual item, or to remove all the items identified by a slice . It is to be lost as per Syntax given below: 

del List[<index>]

del List[<start>:<stop>] 

print(L)

Out[1]: [21, 12, 13, 14, 15] 

del L[1] 

print(L)

Out[2]: [21, 13, 14, 15] 

del L[1:3] 

print(L)

Out[3]: [21, 15] 


List.sort()  

  • Sorts the items of the list in place.  

  • The default order is increasing.  

  • To reverse in decreasing order, reverse=True is used.  

  • Returns nothing. 

L=[13,2,456,1,11,432,32

L.sort() 

print(L)

Out[1]: [1, 2, 11, 13, 32, 432, 456] 

L=[13,2,456,1,11,432,32

L.sort(reverse=True) 

print(L)

Out[2]: [456, 432, 32, 13, 11, 2, 1] 

If the elements within a list consist of complex numbers, sort() will not work.