Python: List Methods

By Xah Lee. Date: . Last updated: .

Basics

list[n:m]
Return a sublist from index n to m.
list[:m]
Same as list[0:m].
list[n:]
Same as list[n:-1].

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

["a","b","c"][0:1] return ['a']

get item
obj[k]
assign item
obj[k] = v
delete item
del obj[k]
join
seq1 + seq2
if exist
obj in seq
format string
s % obj

List Methods

All list methods modifies the list in-place.

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

lst[i] = v
Set ith element to v
lst[i] = v
Set ith element to v
lst[i:j] = lst2
Replace i to j elements by the contents of the lst2
del lst[i]
Remove ith element.
del lst[i:j]
Remove the elements between i to j (not including j). Same as lst[i:j] = []
del lst[i:j:k]
Remove the elements between i to j (not including j), with step k.
lst[i:j:k] = lst2
Replace elements lst[i:j:k] by content of lst2. (lst2 must have same number of elements)

List slice assignment example:

# python 3

# list slice alternate assignment example

e = list(range(20))
e[0:10:2] = ["a"] * 5
print(e)
# ['a', 1, 'a', 3, 'a', 5, 'a', 7, 'a', 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

List Pop, Remove First Element

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

Add to List, Append to List (Push)

lst.append(v)
Append v to the end. Same as lst[len(lst):len(lst)] = [v]
lst.extend(v)
Append v to the end, but flatten v one level if its a list. Same as lst[len(lst):len(lst)] = v
lst.insert(i, v)
Insert at i. Same as lst[i:i] = [v]
# python 3

# list append vs extend

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

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

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

# python 3

# extend example

u = [0,1,2]
v = [0,1,2]
u.extend(["b"])
v.extend("b")

print(u)
# [0, 1, 2, 'b']

print(v)
# [0, 1, 2, 'b']

Find Item

lst.index(v)
Return the index of first occurrence of v. Error if v is not in lst.
lst.index(v, i)
Start at index i
lst.index(v, i, j)
End at index j, not including j
lst.count(v)
Return the number of occurrences of v
lst.remove(v)
Remove first occurrence of v. Error if v is not in lst. Same as del lst[lst.index(v)]
e in lst
Return True if element e is in the list lst, else, False.
# python 3
print [1,2,3,2,7,2].count(2)
# 3

Sort and Reverse

Python: Sort

Python List, Tuple, Dictionary

Python

Regex

Text Processing

Web

Misc