Previous Index Next

Useful Built-in Functions and Methods

len()

The function len returns the length of a list.

>>> num = [10,4,90]
>>> len(num)
3

sum()

Returns the sum of a list.

>>> num = [10,4,90]
>>> sum(num)
104

max()

Returns the largest item in a list.

>>> num = [10,4,90]
>>> max(num)
90

min()

Returns the smallest item in a list.

>>> num = [10,4,90]
>>> min(num)
4

List methods

append()

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()

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()

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]

pop()

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

remove()

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']

insert()

Adds an element at the specified position

>>> t = ['a', 'b', 'c']
>>> t.insert(2,'x')
>>> print(t)
['a', 'b', 'x', 'c']

index()

Returns the index of the first element with the specified value

>>> t = ['a', 'b', 'c']
>>> t.index('b')
1

reverse()

Reverses the order of the list

>>> t = ['a', 'b', 'c']
>>> t.reverse()
>>> print(t)
['c', 'b', 'a']

count()

Returns the number of elements with the specified value

>>> t = [4,8,7,8,8]
>>> t.count(8)
3

The list() Constructor

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]


Previous Index Next