Saturday 13 June 2020

Methods in Python Lists

Lists Methods
The List data type has some important methods to make it useful.

append( ) : Add or append an item to the end of the list.

Syntax: list.append( item )

list = [1, 2, 3, 4, 5, 6]

list.append( 7 )

print( list )

Output:
[1, 2, 3, 4, 5, 6, 7]

extend( ) : Extend the list by appending all the items of the other list

Syntax: list_1.extend( list_2 )

list_1 = [1, 2, 3, 4, 5, 6]

list_2 = [7, 8, 9, 10, 11]

list_1.extend( list_2 )

print( list_1 )

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]


insert( ) : Insert an item at the given position. If position is not provided then the
item will be added to end of the list.

Syntax: list_1.insert( pos, item )

list_1 = [1, 4, 9, 25, 36]

list_1.insert( 3, 16 )

print( list_1 )

list_1.insert( 49)

print( list_1 )


Output:
[1, 4, 9, 16, 25, 36]

[1, 4, 9, 16, 25, 36, 49]

remove( ) : Remove the first occurrence of the given item in the list. If no such item in
the list exists then, it raises ValueError.

Syntax: list_1.remove( item )

list_1 = [1, 4, 9, 25, 36]

list_1.remove( 25 )

print( list_1 )


Output:
[1, 4, 9, 36]

pop( ) : Pop off the item at the given index in the list and return it. If index is not
provided then, it pops off the last item and returns it.

Syntax: list_1.pop( [index] )

list_1 = [1, 4, 9, 25, 36]

list_1.pop( [2] )


Output:
9


count( ) : Return the number of times the given item appears in the list.

Syntax: list_1.count( item )

list_1 = [1, 4, 9, 25, 36, 25]

list_1.count( 25 )


Output:
2


clear( ) : Empty the whole list.

Syntax: list_1.clear(  )

list_1 = [1, 4, 9, 25, 36, 25]

list_1.clear( )

print( list_1 )


Output:
[ ]


sort ( ) : Sort the list items in the preferred order.

Syntax: list_1.sort( key = None, reverse = False  )

list_1 = [5, 1, 4, 6, 0, 8]

list_1.sort( )

print( list_1 )                            // sorts in ascending order

list_1.sort( reverse = True )

print( list_1 )                          // sorts in descending order 


Output:
[0, 1, 4, 5, 6, 8]

[8, 6, 5, 4, 1, 0]


reverse( ) : Reverse the items of the list in place.

Syntax: list_1.reverse(  )

list_1 = [1, 4, 9, 25, 36]

list_1.reverse( )

print( list_1 )


Output:
[36, 25, 9, 4, 1]

9 comments: