The function len returns the length of a list.
>>> num = [10,4,90]
>>> len(num)
3
Returns the sum of a list.
>>> num = [10,4,90]
>>> sum(num)
104
Returns the largest item in a list.
>>> num = [10,4,90]
>>> max(num)
90
Returns the smallest item in a list.
>>> num = [10,4,90]
>>> min(num)
4
Python provides methods that operate on lists. For example, append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t)
['a', 'b', 'c', 'd']
>>> t = ['a', 'b', 'c','d']
>>> y =['m', 'n']
>>> t.append(y)
>>> print(t)
['a', 'b', 'c', 'd', ['m', 'n']]
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
reverse paramter is used to arrange list elements in descending order
>>> L = [34,66,12,89,28,99]
>>> L.sort(reverse = True)
>>> print(L)
[99,89,66,34,28,12]
Delete an element from list at the specified position. If you don't provide an index, it deletes and returns the last element.
>>> n = [10,20,30]
>>> m = n.pop()
>>> print(n)
[10, 20]
>>> print(m)
30
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
['a', 'c']
>>> print(x)
b
If you know the element you want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t)
['a', 'c']
Adds an element at the specified position
>>> t = ['a', 'b', 'c']
>>> t.insert(2,'x')
>>> print(t)
['a', 'b', 'x', 'c']
Returns the index of the first element with the specified value
>>> t = ['a', 'b', 'c']
>>> t.index('b')
1
Reverses the order of the list
>>> t = ['a', 'b', 'c']
>>> t.reverse()
>>> print(t)
['c', 'b', 'a']
Returns the number of elements with the specified value
>>> t = [4,8,7,8,8]
>>> t.count(8)
3
The list() constructor creates a new empty list.
>>> t = list()
>>> print(t)
[]
To convert from a string to a list of characters, you can pass string in list() as parameter.
>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
The range() function can generate a sequence. This sequence can be converted to list by using list() function.
>>> n = list(range(10))
>>> print(n)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]