Python: List Basics

By Xah Lee. Date: . Last updated: .

Creating List

[item_0, item_1, item_2 ]

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

Count Elements

len(list)
Return the count of number of elements.
a = ["more", 4, 6]
print(len(a))
# prints 3

Get a Element

list[n]
Return element in list at index n.
a = ["more", 4, 6]
print(a)
# prints 4

Negative index counts from right.

a = ["more", 4, 6]
print(a[-1])
# prints 6

Change a Element

list[index] = new_value
Change a element's value.
a = [1,2,3]
a = "b"
print(a)
# [1, 2, 'b']

Delete a Element

del list[index]
Delete a element.
a = [3,4,5]
del a
print(a)
# [3, 4]

Get Sublist

list[n:m]
Return a sublist from index n to m.
list[:m]
From beginning to m.
list[n:]
From n to the end, including the end element.

Warning: end index element is not included. For example, mylist[1:2] returns only 1 elements, not 2.

x = [0, 1, 2, 3, 4, 5]
print(x[1:4])
# [1, 2, 3]

Change Sublist

list[index1:index2] = new_list
Replace a sublist by new_list.
a = [1, 2, 3, 4, 5]
a[2:4] = [99, 100]
print(a)
# [1, 2, 99, 100, 5]

Nested Lists

Lists can be nested arbitrarily. Example:

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

Append extra bracket to get element of nested list.

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

Join 2 Lists

list1 + list2
Join 2 lists into 1.
b = ["a", "b"] + [7, 6]
print(b)
# ['a', 'b', 7, 6]