
Python List (Iterate, append, reverse, pop, etc)
A list is an ordered set of objects in Python.
a = [1, 2, 3]
Iterate
a = ['com', 'org', 'net']
for i in a:
print(i)
# com
# org
# net
Get element by index
a = ['com', 'org', 'net']
print(a[0]) # com
print(a[1]) # org
print(a[2]) # net
The index of the first element is 0.
Append
a = [1, 2, 3]
a.append(7)
print(a) # [1, 2, 3, 7]
Addition
x = [1, 2]
y = [5, 6, 7]
z = x + y
print(z) # [1, 2, 5, 6, 7]
Reverse
a = [1, 2, 3]
a.reverse()
print(a) # [3, 2, 1]
Reverse method reverses an order.
Remove from index
a = ['com', 'org', 'net', 'gov']
a.pop(1)
print(a) # ['com', 'net', 'gov']
Or use built-in function del
.
a = ['com', 'org', 'net', 'gov']
del a[2]
print(a) # ['com', 'org', 'gov']
Extend
x = [1, 2]
y = [5, 6, 7]
x.extend(y)
print(x) # [1, 2, 5, 6, 7]
The extend
and append
are confusing. The extend
gets all the items from the argument list and appends those to the list. But append
simply appends the argument as an item.
x1 = [1, 2]
x2 = [1, 2]
y = [5, 6, 7]
x1.extend(y)
x2.append(y)
print(x1) # [1, 2, 5, 6, 7]
print(x2) # [1, 2, [5, 6, 7]]
Comments
Powered by Markdown