Python: List Methods

By Xah Lee. Date: . Last updated: .

Basics

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

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

Sequence Operators
purposesyntax
get itemobj[k]
assign itemobj[k] = v
delete itemdel obj[k]
joinseq1 + seq2
if existobj in seq
format strings % obj

List Methods

All list methods modifies the list in-place.

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

generic add/remove/set
SyntaxMeaning
lst[i] = vset ith element to v
lst[i] = vset ith element to v
lst[i:j] = lst2replace 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] = lst2replace 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

pop
SyntaxMeaning
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)

add to list
SyntaxMeaning
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

finding item
SyntaxMeaning
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)]
finding item
SyntaxMeaning
e in lstreturn True if element e is in the list lst, else, False. [see Python's Context Dependent Syntax Soup: “in” And “not in”]
# python 3
print [1,2,3,2,7,2].count(2)
# 3

Sort and Reverse

Python: Sort

Python List, Tuple, Dictionary

  1. List Basics
  2. Loop Thru List
  3. Map f to List
  4. Copy Nested List
  5. List Comprehension
  6. List Methods
  7. Sort
  8. Dictionary
  9. Loop Thru Dict
  10. Dict Methods
  11. Tuple
  12. Sets, Union, Intersection

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

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File 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

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation