Python: List Basics

By Xah Lee. Date: . Last updated: .

Creating List

[item_0, item_1, item_2, ]

# python 3

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

Count Elements

len(list)
Return the count of number of elements.
# python 3

a = ["more", 4, 6]
print(len(a))
# prints 3

Get a Element

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

Negative index counts from right.

# python 3

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

Change a Element

list[index] = new_value
Change a element's value.
# python 3

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

Delete a Element

del list[index]
Delete a element.
# python 3

a = [3,4,5]
del a[2]
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.

# python 3

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.
# python 3

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.

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

Join 2 Lists

list1 + list2
Join 2 lists into 1.
# python 3

b = ["a", "b"] + [7, 6]
print(b)
# ['a', 'b', 7, 6]

Python List, Tuple, Dictionary

Python

Regex

Text Processing

Web

Misc