![]() |
python list methods and functions |
Get list Length
Using len() Function you can get a length of list .
list = [ 'mango' ,' banana', 'apple' ]
print(len(list))
Output
3
type() Function
type() Function is used for get type of list
list = [ 'mango' ,' banana', 'apple' ]
print(type(list))
Output
< class, 'list' >
list() Constructor
list1 = list(( 'mango' ,' banana', 'apple' ))
print(list1)
[ 'mango' ,' banana', 'apple' ]
Add Items in List
insert () Method
Inserting a Item in list without any replacement with existing item
we can use insert() Method for insert item in list
insert () methods can insert an item with specified Index.
Example
list = [ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple' ]
list.insert(2," banana ")
print(list)
Output
[ 'mango' , 'apple', 'banana' , 'kiwi' , 'orange' , 'pineapple' ]
Example
list = [ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple' ]
list.append(" banana ")
print(list)
Output
[ 'mango' , 'apple' , 'kiwi' , 'orange' , 'pineapple', 'banana' ]
extend() Method
extend() Method is used for add list items in another list
Example
list1 = [ 'mango' , 'apple', 'kiwi' ]
list2 = ['orange' , 'pineapple' ]
list1.extend(list2)
print(list1)
Output
[ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple' ]
Remove Items
remove() Method
remove() Method remove the specified Items from list
Example
list = [ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple']
list.remove('apple')
print(list)
Output
[ 'mango' , 'kiwi' , 'orange' , 'pineapple' ]
pop() Method
pop() Method remove the specified Index from list
Example
list = [ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple']
list.pop(1)
print(list)
Output
[ 'mango' , 'kiwi' , 'orange' , 'pineapple' ]
If you not specified the Index in pop method , by default remove the last index
Example
list = [ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple']
list.pop()
print(list)
Output
['mango' , 'apple' , 'kiwi' , 'orange' ]
'del' keyword
'del' Keyword is used for remove the specified index from list
Example
list = [ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple']
del list[0]
print(list)
Output
[ 'apple', 'kiwi' , 'orange' , 'pineapple']
clear() Method
clear() method is remove the all items from list , list is exist but not has Items
Example
list = [ 'mango' , 'apple', 'kiwi' , 'orange' , 'pineapple']
list.clear()
print(list)
Output
[ ]