Python: List

By Xah Lee. Date: . Last updated: .

Syntax of List (Literal Expression to Create a List)

[x0, x1, x2 etc]

x = [1, 2, "m"]
print(x)
# [1, 2, 'm']

list can have items of different types.

Total Number of Items

len(list)
Return the count of number of items.
x = [0, 1, 2]
print(len(x) == 3)

Check Existence

x in list
check if exist.
x = [0, 1, 2]
print(2 in x)

x = ["a", "b", "c"]
print("b" in x)
x not in list
return true if not in list.
x = [0, 1, 2]
print(3 not in x)

x = ["a", "b", "c"]
print("m" not in x)

Get one Item

list[i]
Return ith item.
x = ["a", "b", "c"]
print(x[1] == "b")

Index starts at 0.

Negative index counts from right.

x = ["a", "b", "c"]
print(x[-1] == "c")

Set/Change One Item

list[i] = newValue
Change a item's value.
x = [1, 2, 3]
x[2] = "b"
print(x == [1, 2, "b"])

Delete One Item

del list[i]
Delete ith item.
x = ["a", "b", "c"]
del x[1]
print(x == ["a", "c"])

Get Sublist

list[i:j]
Return a sublist from index i to j, exclude j.
x = [0, 1, 2, 3, 4, 5]
print(x[1:4] == [1, 2, 3])
list[:j]
From beginning to j.
list[i:]
From i to the end, including the end item.
x = [0, 1, 2, 3, 4, 5]
print(x[3:] == [3, 4, 5])

Delete Sublist

del list[i:j]
delete the items between i to j (excluding j).
del list[i:j:k]
delete the items between i to j (excluding j), with step k.

Replace Sublist

list[i:j] = list2
Replace i to j items by the contents of the list2
x = [1, 2, 3, 4, 5]
x[2:4] = [99, 100]
print(x == [1, 2, 99, 100, 5])
list[i:j:k] = list2
Replace items list[i:j:k] by content of list2. (list2 must have same number of items)
# 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]

Nested Lists

Lists can be nested arbitrarily. Example:

x = [3, 4, [7, 8]]

Append extra bracket to get item of nested list.

x = [3, 4, [7, 8]]
print(x[2][1] == 8)

Join Lists

list1 + list2
Join two lists into one.

see also append. Python: List Methods

x = [1, 2] + [7, 6]
print(x == [1, 2, 7, 6])

Python Data Structure