List is used to store multiple values. list is created using square bracket.
l = [10, 20, 30, 40, 50]
List indexing
print(l[0]) # 10 print(l[1]) # 20
List splitting
print(l[0: 3]) # [10, 20, 30]
Change list item
l[0]= 100 print(l) # 100, 20, 30, 40, 50
List methods
count() | Count number of elements of specified value |
l=[1,2,3,1] print(l.count(1)) # 2
append() | Append new value to list |
l=[1,2,3] l.append(100) print(l) # [1,2,3,100]
clear() | Remove all elements from a list |
l=[1,2,3] l.clear() print(l) # []
copy() | Return copy of a list |
x=[1,2,3] y=x.copy() print(y) # [1, 2,3]
extend() | Add one list elements to other list |
x=[1,2,3] y=[100,200] x.extend(y) print(x) # [1,2,3, 100,200]
index() | Return index of specified item from a list |
x=[1,2,3] print(x.index(1)) # 0
insert() | Insert new item at specified index |
x=[10, 20, 30] x.insert(0, 100) print(x) # [100, 10, 20, 30]
pop() | Remove last item from a list |
x=[10, 20, 30] x.pop() print(x) # [10, 20]
reverse() | Reverse a list |
x=[1,2,3] print(x) # [1,2,3] x.reverse() print(x) # [3,2,1]
remove() | Remove the specified item from a list |
x=[1,2,3] x.remove(2) print(x) # [1, 3]
sort() | Sort list items in ascending or descending order |
x=[1, 21, 3] x.sort() print(x) # [1, 3, 21] x.sort(reverse=True) print(x) # [21, 3, 1]