Python - Lists

python list

Python lists store data sequentially and are mutable, allowing for dynamic changes to their elements.


my_list = ['item1', 2, 'item3', 4, 'item5', 2, 4]

List indexes are zero-based, meaning they start counting from zero.


Access List Items

To access a list item, use the index inside square brackets [index].

x = [4, 32, 8, 10, 7, 32, 76]
print(x[2]) # 8

Add List Items

To add a list item, you have four options:

x = [1]
x.append(2)
x.insert(1, 3)

Remove List Items

To remove a list item, you have three options:

x = [5, 4, 3, 2, 1]
x.pop(3)
x.remove(4)
del x[0]

Edit List Items

To edit a list item, use the index operator [index] with assignment operator =.

x = ["Felipe", "Fernando", "Roberto", "Maria", "Joana"]
x[0] = "John"
x[2:4] = [ "Ana", "Micael" ]

Join Lists

To join lists, you have two options:

x = [1,2,3]
x = x + [4,5,6]
x.extend((7,8,9))

List Length

To obtain the length of a list use len(x).

x = ["A", "B", "C", 'a', 'b', 'c']
print(len(x)) # 6

List Slicing

To extract a subset of elements from a list use the slicing syntax list[start:end].

[start:end]
[:end] # 0 to end
[start:] # start to end
x = ['a', 'b', 'c', 'd', 'e', 'f']
y = x[2:4]