Python: List Methods

, , …,

This page is a complete list of Python list methods. For a basic tutorial on list, see: Python: List Basics

Note: index start at 0. 0th item meas first item. Ending index does not include itself.

print ["a","b","c"][0:1]        # ['a']

All list methods modifies the list in-place.

List Elements Extraction, Slice, Generic Add/Remove/Set List Elements

generic add/remove/set
[i] = vset ith element to v
[i] = vset ith element to v
[i:j] = ℓ2replace i to j elements by the contents of the ℓ2
del [i]remove ith element.
del [i:j]remove the elements between i to j (not including j). Same as [i:j] = []
del [i:j:k]remove the elements between i to j (not including j), with step k.
[i:j:k] = ℓ2replace elements [i:j:k] by content of ℓ2. (ℓ2 must have same number of elements)

List slice assignment example:

# -*- coding: utf-8 -*-
# python

# list slice assignment example

e = range(30)
e[0:30:3] = ["a"] * 10
print e

# ['a', 1, 2, 'a', 4, 5, 'a', 7, 8, 'a', 10, 11, 'a', 13, 14, 'a', 16, 17, 'a', 19, 20, 'a', 22, 23, 'a', 25, 26, 'a', 28, 29]

List Pop, Remove First Element

.pop()remove last element and return it.
.pop(i)remove ith element and return it. Same as v = [i]; del [i]; return v

Add to List, Append to List (Push)

add to list
.append(v)append v to the end. Same as [len():len()] = [v]
.extend(v)append v to the end, but flatten v one level if its a list. Same as [len():len()] = v
.insert(i, v)insert at i. Same as [i:i] = [v]
# -*- coding: utf-8 -*-
# python

# list append and extend

e = range(3)
e.append(["a",[8]])             # [0, 1, 2, ['a', [8]]]
print e

u = range(3)
u.extend(["a",[8]])             # [0, 1, 2, 'a', [8]]
print u

in list.extend(v), v can be a atom or list. If list, it is flattened one level.

# -*- coding: utf-8 -*-
# python

# ‹list›.extend(‹v›)

u = range(3)
v = range(3)
u.extend(["b"])                 # [0, 1, 2, 'b']
v.extend("b")                   # [0, 1, 2, 'b']
print u
print v

Finding Item

finding item
.index(v)return the index of first occurrence of v. Error if v is not in .
.index(v, i)start at index i
.index(v, i, j)end at index j, not including j
.count(v)return the number of occurrences of v
.remove(v)remove first occurrence of v. Error if v is not in . Same as del [.index(v)]
finding item
e in return True if element e is in the list , else, False. 〔➤ Python's Context Dependent Syntax Soup: … in … And … not in …
# list count example
print [1,2,3,2,7,2].count(2)    # 3

Sort & Reverse

sort & reverse
.reverse()reverses the items of in place.
.sort()sort the items of in place
.sort(f)using predicate function f to sort. f takes 2 args, and return {1, 0, -1}, but any int works. The sign indicates order.
.sort(key=f)sort using f to extract a “key”. f takes 1 arg. Result is compared using cmp(). 〔➤ Python, Perl: Sort Matrix, Object, Math of Sorting
.sort(key=f, reverse=true/false)

5. Built-in Types — Python v2.7.6 documentation #mutable-sequence-types

blog comments powered by Disqus