Python Basic: List and Index
Goal¶
This post aims to introduce the operation around list
and index
often used for data structure and algorithm. This post covers the following operations:
- Create a list
- Access to an element
- Remove an element
- Divide a list
- Scan a list
from icecream import ic
Create a list
¶
# Empty List
a0 = list()
# Create a list by elemnts
a1 = [0, 1, 2, 3, 4, 5]
ic(a0, a1);
When to create a list from p
to q
as an incremental list of int
, we can use range
. Note that p
is included but q
is not included. If we don't specify p
, it becomes 0
by default.
p = 0
q = 10
ic(list(range(p, q)), list(range(10)));
Access to an element by index¶
Index is starting from 0. If you would like to access to N-th element, you need to specify by (N-1)
a2 = list(range(10))
# 1st element
ic(a2[0])
# 5th element
ic(a2[4]);
# The last element
ic(a2[-1]);
# The 2nd last element
ic(a2[-2]);
Slice a list by a range of index¶
When we want to extract a set of elements from p
th element to q
th element, we can use :
. If we want to specify the range counting from the last element, we could use negative index like -p
.
p = 2 # From 3rd element (included)
q = 5 # To 6th element (excluded)
a2 = list(range(10))
ic(p, q, a2, a2[p:q]);
ic(q, a2[0:q], a2[:q]);
ic(q, a2[-3:], a2[-3:-1]);
Remove an element¶
Remove an element by pop
¶
a2 = list(range(10))
# Get the 1st element and remove it from a list
e0 = a2.pop(0)
ic(e0, a2);
# Get the last element and remove it from a list
e1 = a2.pop(-1)
ic(e1, a2);
Divide a list into before and after by a pivot element¶
When we want to recursively apply a process to before- and after- sublist divided by a pivot element, we need an operation like below:
a2 = list(range(10))
i = 3 # index for the pivot value
ic(a2[:i], a2[i], a2[i+1:]);
Scan a list by for
loop¶
- Use
enumerate
to get each index and element itself - Use
range
to generate an index and access each element by index
a3 = [3,4,1,7,0]
for i, e in enumerate(a3):
ic(i, e)
a3 = [3,4,1,7,0]
for i in range(len(a3)):
ic(i, a3[i])
Comments
Comments powered by Disqus