Python lists and it's essential functions

Python lists and it's essential functions

A list in Python is used to store the sequence of various types of data. Python lists are mutable type, it means that we can modify it's element after it is created.

Essential List Functions: 1. append( elmnt ) It adds an element at the end of the list.

fruits = ["apple", "banana", "cherry"] fruits.append( "orange" ) print( fruits )

[‘apple', 'banana', 'cherry', 'orange']

2. clear() It remove all elements from the list

fruits = ['apple', 'banana', 'cherry', 'orange'] fruits.clear() print( fruits )

[]

3. copy() This method returns a copy of the specified list.

fruits = ['apple', 'banana', 'cherry', 'orange'] x = fruits.copy() print( fruits )

['apple', 'banana', 'cherry', 'orange']

4. count( value ) It returns the number of elements with the specified value

fruits = ['apple', 'banana', 'cherry'] x = fruits.count( "cherry" )

it will return 1 since there is only one 'cherry' element

print( fruits )

1

5. extend( iterable ) It adds the elements of a list (or any iterable) to the end of the current list.

fruits = [ 'apple', 'banana', 'cherry' ] cars = [ 'Ford', 'BMW', 'Volvo' ] fruits.extend( cars ) print( fruits )

[‘apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

6. index( elmnt ) It returns the index of the first element with the specified value.

fruits = [ 'apple', 'banana', 'cherry' ] x = fruits.index("cherry") print( x )

2

7. insert( pos, elmnt ) It adds an element at the specified position

fruits = ['apple', 'banana', 'cherry'] fruits.insert( 1, "orange" ) print( fruits )

['apple', 'orange', 'banana', 'cherry']

8. pop( pos ) It removes the element at the specified position

fruits = ['apple', 'banana', 'cherry'] fruits.pop( 1 ) print( fruits )

['apple', 'cherry']

9. remove( elmnt ) It removes the first item with the specified value

fruits = ['apple', 'banana', 'cherry'] fruits.remove( "banana" ) print( fruits )

['apple', 'cherry']

10. reverse() It reverses the order of the list

fruits = ['apple', 'banana', 'cherry'] fruits.reverse() print( fruits )

['cherry', 'banana', 'apple']

11. sort( reverse = True|False, key = myFunc ) The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s).

reverse : ascending or descending order key : A function to specify the sorting criteria(s)

image.png

Important points on list: Items in a list need not be of the same type. Items in the list are separated with the comma (,) and enclosed with the square brackets [] A list can also have another list as an item. Lists are mutable whereas tuple are immutable.

Thank you for reading the entire post ! Keep sharing it.

I will soon share a similar thread on Python Tuple !!!