In today's post I will present some of the most used list functions.
- len, display list length. Example:
mylist = [1, 'two', 'xyz', 8.35, True]
print(len(mylist))
#output
5
- insert, add an item to the list specified. Example:
mylist = [1, 'two', 'xyz', 8.35, True]
mylist.insert(2, False)
print(mylist)
#output
[1, 'two', False, 'xyz', 8.35, True]
- append, add an item to the list at the end of list. Example:
mylist = [1, 'two', 'xyz', 8.35, True]
mylist.append('abc')
print(mylist)
#output
[1, 'two', 'xyz', 8.35, True, 'abc']
- remove, delete an item from list. Example:
mylist = [1, 'two', 'xyz', 8.35, True, 'abc']
mylist.remove('two')
print(mylist)
#output
[1, 'xyz', 8.35, True, 'abc']
- del, delete entire list. Example:
mylist = [1, 'xyz', 8.35, True, 'abc']
del mylist
print(mylist)
#output
Traceback (most recent call last):
File "<PATH>\test.py", line 3, in <module> print(mylist)
NameError: name 'mylist' is not defined. Did you mean: 'list'?
- clear, empty the list. Example:
mylist = [1, 'xyz', 8.35, True, 'abc']
mylist.clear()
print(mylist)
#output
[]
- pop, remove last item from list, and return it. Example:
mylist = [1, 'xyz', 8.35, True, 'abc']
last_item=mylist.pop()
print(last_item)
print(mylist)
#output
abc
[1, 'xyz', 8.35, True]
- copy, make a copy of list. Example:
mylist = [1, 'xyz', 8.35, True, 'abc']
listNo2 = mylist.copy()
print(listNo2)
[1, 'xyz', 8.35, True, 'abc']
- extend, add item of other list2 to the end of list1. Example:
list1 = [1, 'xyz', 8.35, True, 'abc']
list2 = ['bb', 25]
list1.extend(list2)
print(list1)
#output
[1, 'xyz', 8.35, True, 'abc', 'bb', 25]
- count, return the number of occurrences of item in list. Example:
mylist = [1, 'xyz', 8.35, True, 'xyz', 'abc']
nb=mylist.count('xyz')
print(nb)
#output
2
- index, return index of the first items with specified value. Example:
mylist = [1, 'xyz', 8.35, True, 'xyz', 'abc']
ni=mylist.index('xyz')
print(ni)
#output
1
- reverse, this method reverses the list items. Example:
mylist = [1, 'xyz', 8.35, True, 'xyz', 'abc']
mylist.reverse()
print(mylist)
#output
['abc', 'xyz', True, 8.35, 'xyz', 1]
- sort, this method sorts the items of list. Example:
list1 = [5, 53, 7, 22, 18, 31]
list1.sort()
print(list1)
#output
[5, 7, 18, 22, 31, 53]
Observation: list items need to be sortable, means if we have a list with mixed items, numbers, strings, etc, it can't be sorted. Example:
mylist = [1, 'xyz', 8.35, True, 'xyz', 'abc']
mylist.sort()
print(mylist)
#output
Traceback (most recent call last):
File "<PATH>\test.py", line 2, in <module> mylist.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
#-> error is expected