Python: List Methods

By Xah Lee. Date: . Last updated: .

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
SyntaxMeaning
[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
SyntaxMeaning
.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
SyntaxMeaning
.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
SyntaxMeaning
.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
SyntaxMeaning
e in return True if element e is in the list , else, False. 〔►see Python's Context Dependent Syntax Soup: … in … And … not in …
# list count example
print [1,2,3,2,7,2].count(2)    # 3

Sort and Reverse

sort and reverse
SyntaxMeaning
.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(). [see 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

If you have a question, put $5 at patreon and message me.

Python by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help

String

  1. Quote String
  2. String Operations
  3. String Methods
  4. Format String

Branching, Loop

  1. True, False
  2. if then else
  3. for, while, Loops

List

  1. List Basics
  2. Loop Thru List
  3. Map Function to List
  4. List Comprehension
  5. List Methods

Dictionary

  1. Dictionary
  2. Loop Thru Dictionary
  3. Dictionary Methods

Function

  1. Function Parameter

Class

  1. Class and Object

Module

  1. List Modules
  2. Write a Module

Unicode

  1. Python + Unicode 🐍
  2. Process Unicode
  3. Convert File Encoding

Common Tasks

  1. Read/Write File
  2. Traverse Directory
  3. Complex Numbers
  4. Get Env Var
  5. JSON

Regex

  1. Regex Basics
  2. Split Line by Regex
  3. Regex Reference

Advanced

  1. Copy Nested List
  2. Tuple vs List
  3. Sets, Union, Intersection
  4. Closure in Python 2
  5. Decorator
  6. Append String in Loop
  7. Timing Functions with timeit
  8. Keyword Argument Default Value Unstable
  1. Find Python Script Path
  2. Manipulate Path
  3. Sort Matrix, Object

Find/Replace

  1. Find/Replace Strings on Multiple Files
  2. Find/Replace Multi-line Strings in a Dir
  3. Find/Replace Mulitple Pairs of Strings
  4. Find/Replace by Regex
  5. Find/Replace Strings in Unicode Files
  6. Python, Perl: Find/Replace Strings in a File

HTML/Web

  1. Sending Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST
  1. A Script to check HTML file size
  2. Thumbnail Generation

Misc

  1. System Call
  2. Decompress Gzip

reference