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: Sort]
.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
  4. Quote String
  5. String Operations
  6. String Methods
  7. Format String
  8. True, False
  9. if then else
  10. for, while, Loops
  11. List Basics
  12. Loop Thru List
  13. Map Function to List
  14. List Comprehension
  15. List Methods
  16. Dictionary
  17. Loop Thru Dict
  18. Dict Methods
  19. Function
  20. Class
  21. List Modules
  22. Write a Module
  23. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. Manipulate Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST
  5. Check Page Load Size
  6. Thumbnail Generation

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Complex Numbers

Advanced

  1. Sort
  2. Copy Nested List
  3. Tuple vs List
  4. Sets, Union, Intersection
  5. Closure in Python 2
  6. Decorator
  7. Append String in Loop
  8. Timing f timeit
  9. Keyword Arg Default Value Unstable

Reference