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:

  1. Create a list
  2. Access to an element
  3. Remove an element
  4. Divide a list
  5. Scan a list
In [44]:
from icecream import ic

Create a list

In [45]:
# Empty List
a0 = list()

# Create a list by elemnts
a1 = [0, 1, 2, 3, 4, 5]

ic(a0, a1);
ic| a0: [], a1: [0, 1, 2, 3, 4, 5]

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.

In [46]:
p = 0
q = 10
ic(list(range(p, q)), list(range(10)));
ic| list(range(p, q)): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    list(range(10)): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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)

In [52]:
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]);
ic| a2[0]: 0
ic| a2[4]: 4
ic| a2[-1]: 9
ic| a2[-2]: 8

Slice a list by a range of index

When we want to extract a set of elements from pth element to qth element, we can use :. If we want to specify the range counting from the last element, we could use negative index like -p.

In [48]:
p = 2 # From 3rd element (included) 
q = 5 # To 6th element (excluded)
a2 = list(range(10))
ic(p, q, a2, a2[p:q]);
ic| p: 2, q: 5, a2: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], a2[p:q]: [2, 3, 4]
In [49]:
ic(q, a2[0:q], a2[:q]);
ic| q: 5, a2[0:q]: [0, 1, 2, 3, 4], a2[:q]: [0, 1, 2, 3, 4]
In [50]:
ic(q, a2[-3:], a2[-3:-1]);
ic| q: 5, a2[-3:]: [7, 8, 9], a2[-3:-1]: [7, 8]

Remove an element

Remove an element by pop

In [54]:
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);
ic| e0: 0, a2: [1, 2, 3, 4, 5, 6, 7, 8, 9]
ic| e1: 9, a2: [1, 2, 3, 4, 5, 6, 7, 8]

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:

In [56]:
a2 = list(range(10))

i = 3 # index for the pivot value

ic(a2[:i], a2[i], a2[i+1:]);
ic| a2[:i]: [0, 1, 2], a2[i]: 3, a2[i+1:]: [4, 5, 6, 7, 8, 9]

Scan a list by for loop

  1. Use enumerate to get each index and element itself
  2. Use range to generate an index and access each element by index
In [61]:
a3 = [3,4,1,7,0]

for i, e in enumerate(a3):
    ic(i, e)
ic| i: 0, e: 3
ic| i: 1, e: 4
ic| i: 2, e: 1
ic| i: 3, e: 7
ic| i: 4, e: 0
In [62]:
a3 = [3,4,1,7,0]

for i in range(len(a3)):
    ic(i, a3[i])
ic| i: 0, a3[i]: 3
ic| i: 1, a3[i]: 4
ic| i: 2, a3[i]: 1
ic| i: 3, a3[i]: 7
ic| i: 4, a3[i]: 0

Comments

Comments powered by Disqus